
/*!
 * jQuery JavaScript Library v1.8.3
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright 2012 jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time)
 */
(function( window, undefined ) {
var
	// A central reference to the root jQuery(document)
	rootjQuery,

	// The deferred used on DOM ready
	readyList,

	// Use the correct document accordingly with window argument (sandbox)
	document = window.document,
	location = window.location,
	navigator = window.navigator,

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// Save a reference to some core methods
	core_push = Array.prototype.push,
	core_slice = Array.prototype.slice,
	core_indexOf = Array.prototype.indexOf,
	core_toString = Object.prototype.toString,
	core_hasOwn = Object.prototype.hasOwnProperty,
	core_trim = String.prototype.trim,

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Used for matching numbers
	core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,

	// Used for detecting and trimming whitespace
	core_rnotwhite = /\S/,
	core_rspace = /\s+/,

	// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,

	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,

	// Matches dashed string for camelizing
	rmsPrefix = /^-ms-/,
	rdashAlpha = /-([\da-z])/gi,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return ( letter + "" ).toUpperCase();
	},

	// The ready event handler and self cleanup method
	DOMContentLoaded = function() {
		if ( document.addEventListener ) {
			document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
			jQuery.ready();
		} else if ( document.readyState === "complete" ) {
			// we're here because readyState === "complete" in oldIE
			// which is good enough for us to call the dom ready!
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	},

	// [[Class]] -> type pairs
	class2type = {};

jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem, ret, doc;

		// Handle $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;
					doc = ( context && context.nodeType ? context.ownerDocument || context : document );

					// scripts is true for back-compat
					selector = jQuery.parseHTML( match[1], doc, true );
					if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
						this.attr.call( selector, context, true );
					}

					return jQuery.merge( this, selector );

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[2] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || rootjQuery ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.8.3",

	// The default length of a jQuery object is 0
	length: 0,

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	toArray: function() {
		return core_slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" ) {
			ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
		} else if ( name ) {
			ret.selector = this.selector + "." + name + "(" + selector + ")";
		}

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	ready: function( fn ) {
		// Add the callback
		jQuery.ready.promise().done( fn );

		return this;
	},

	eq: function( i ) {
		i = +i;
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, i + 1 );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	slice: function() {
		return this.pushStack( core_slice.apply( this, arguments ),
			"slice", core_slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},

	end: function() {
		return this.prevObject || this.constructor(null);
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: core_push,
	sort: [].sort,
	splice: [].splice
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function( deep ) {
		if ( window.$ === jQuery ) {
			window.$ = _$;
		}

		if ( deep && window.jQuery === jQuery ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( !document.body ) {
			return setTimeout( jQuery.ready, 1 );
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );

		// Trigger any bound ready events
		if ( jQuery.fn.trigger ) {
			jQuery( document ).trigger("ready").off("ready");
		}
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	isWindow: function( obj ) {
		return obj != null && obj == obj.window;
	},

	isNumeric: function( obj ) {
		return !isNaN( parseFloat(obj) ) && isFinite( obj );
	},

	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ core_toString.call(obj) ] || "object";
	},

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		try {
			// Not own constructor property must be Object
			if ( obj.constructor &&
				!core_hasOwn.call(obj, "constructor") &&
				!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
				return false;
			}
		} catch ( e ) {
			// IE8,9 Will throw exceptions on certain host objects #9897
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.

		var key;
		for ( key in obj ) {}

		return key === undefined || core_hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	error: function( msg ) {
		throw new Error( msg );
	},

	// data: string of html
	// context (optional): If specified, the fragment will be created in this context, defaults to document
	// scripts (optional): If true, will include scripts passed in the html string
	parseHTML: function( data, context, scripts ) {
		var parsed;
		if ( !data || typeof data !== "string" ) {
			return null;
		}
		if ( typeof context === "boolean" ) {
			scripts = context;
			context = 0;
		}
		context = context || document;

		// Single tag
		if ( (parsed = rsingleTag.exec( data )) ) {
			return [ context.createElement( parsed[1] ) ];
		}

		parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
		return jQuery.merge( [],
			(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
	},

	parseJSON: function( data ) {
		if ( !data || typeof data !== "string") {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );

		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
			.replace( rvalidtokens, "]" )
			.replace( rvalidbraces, "")) ) {

			return ( new Function( "return " + data ) )();

		}
		jQuery.error( "Invalid JSON: " + data );
	},

	// Cross-browser xml parsing
	parseXML: function( data ) {
		var xml, tmp;
		if ( !data || typeof data !== "string" ) {
			return null;
		}
		try {
			if ( window.DOMParser ) { // Standard
				tmp = new DOMParser();
				xml = tmp.parseFromString( data , "text/xml" );
			} else { // IE
				xml = new ActiveXObject( "Microsoft.XMLDOM" );
				xml.async = "false";
				xml.loadXML( data );
			}
		} catch( e ) {
			xml = undefined;
		}
		if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
			jQuery.error( "Invalid XML: " + data );
		}
		return xml;
	},

	noop: function() {},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && core_rnotwhite.test( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
	},

	// args is for internal usage only
	each: function( obj, callback, args ) {
		var name,
			i = 0,
			length = obj.length,
			isObj = length === undefined || jQuery.isFunction( obj );

		if ( args ) {
			if ( isObj ) {
				for ( name in obj ) {
					if ( callback.apply( obj[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( obj[ i++ ], args ) === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in obj ) {
					if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
						break;
					}
				}
			}
		}

		return obj;
	},

	// Use native String.trim function wherever possible
	trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
		function( text ) {
			return text == null ?
				"" :
				core_trim.call( text );
		} :

		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				( text + "" ).replace( rtrim, "" );
		},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var type,
			ret = results || [];

		if ( arr != null ) {
			// The window, strings (and functions) also have 'length'
			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
			type = jQuery.type( arr );

			if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
				core_push.call( ret, arr );
			} else {
				jQuery.merge( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		var len;

		if ( arr ) {
			if ( core_indexOf ) {
				return core_indexOf.call( arr, elem, i );
			}

			len = arr.length;
			i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

			for ( ; i < len; i++ ) {
				// Skip accessing in sparse arrays
				if ( i in arr && arr[ i ] === elem ) {
					return i;
				}
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var l = second.length,
			i = first.length,
			j = 0;

		if ( typeof l === "number" ) {
			for ( ; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}

		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, inv ) {
		var retVal,
			ret = [],
			i = 0,
			length = elems.length;
		inv = !!inv;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var value, key,
			ret = [],
			i = 0,
			length = elems.length,
			// jquery objects are treated as arrays
			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( key in elems ) {
				value = callback( elems[ key ], key, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		var tmp, args, proxy;

		if ( typeof context === "string" ) {
			tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		args = core_slice.call( arguments, 2 );
		proxy = function() {
			return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	},

	// Multifunctional method to get and set values of a collection
	// The value/s can optionally be executed if it's a function
	access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
		var exec,
			bulk = key == null,
			i = 0,
			length = elems.length;

		// Sets many values
		if ( key && typeof key === "object" ) {
			for ( i in key ) {
				jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
			}
			chainable = 1;

		// Sets one value
		} else if ( value !== undefined ) {
			// Optionally, function values get executed if exec is true
			exec = pass === undefined && jQuery.isFunction( value );

			if ( bulk ) {
				// Bulk operations only iterate when executing function values
				if ( exec ) {
					exec = fn;
					fn = function( elem, key, value ) {
						return exec.call( jQuery( elem ), value );
					};

				// Otherwise they run against the entire set
				} else {
					fn.call( elems, value );
					fn = null;
				}
			}

			if ( fn ) {
				for (; i < length; i++ ) {
					fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
				}
			}

			chainable = 1;
		}

		return chainable ?
			elems :

			// Gets
			bulk ?
				fn.call( elems ) :
				length ? fn( elems[0], key ) : emptyGet;
	},

	now: function() {
		return ( new Date() ).getTime();
	}
});

jQuery.ready.promise = function( obj ) {
	if ( !readyList ) {

		readyList = jQuery.Deferred();

		// Catch cases where $(document).ready() is called after the browser event has already occurred.
		// we once tried to use readyState "interactive" here, but it caused issues like the one
		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			setTimeout( jQuery.ready, 1 );

		// Standards-based browsers support DOMContentLoaded
		} else if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );

		// If IE event model is used
		} else {
			// Ensure firing before onload, maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", DOMContentLoaded );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );

			// If IE and not a frame
			// continually check to see if the document is ready
			var top = false;

			try {
				top = window.frameElement == null && document.documentElement;
			} catch(e) {}

			if ( top && top.doScroll ) {
				(function doScrollCheck() {
					if ( !jQuery.isReady ) {

						try {
							// Use the trick by Diego Perini
							// http://javascript.nwbox.com/IEContentLoaded/
							top.doScroll("left");
						} catch(e) {
							return setTimeout( doScrollCheck, 50 );
						}

						// and execute any waiting functions
						jQuery.ready();
					}
				})();
			}
		}
	}
	return readyList.promise( obj );
};

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};

// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
	var object = optionsCache[ options ] = {};
	jQuery.each( options.split( core_rspace ), function( _, flag ) {
		object[ flag ] = true;
	});
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		( optionsCache[ options ] || createOptions( options ) ) :
		jQuery.extend( {}, options );

	var // Last fire value (for non-forgettable lists)
		memory,
		// Flag to know if list was already fired
		fired,
		// Flag to know if list is currently firing
		firing,
		// First callback to fire (used internally by add and fireWith)
		firingStart,
		// End of the loop when firing
		firingLength,
		// Index of currently firing callback (modified by remove if needed)
		firingIndex,
		// Actual callback list
		list = [],
		// Stack of fire calls for repeatable lists
		stack = !options.once && [],
		// Fire callbacks
		fire = function( data ) {
			memory = options.memory && data;
			fired = true;
			firingIndex = firingStart || 0;
			firingStart = 0;
			firingLength = list.length;
			firing = true;
			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
					memory = false; // To prevent further calls using add
					break;
				}
			}
			firing = false;
			if ( list ) {
				if ( stack ) {
					if ( stack.length ) {
						fire( stack.shift() );
					}
				} else if ( memory ) {
					list = [];
				} else {
					self.disable();
				}
			}
		},
		// Actual Callbacks object
		self = {
			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {
					// First, we save the current length
					var start = list.length;
					(function add( args ) {
						jQuery.each( args, function( _, arg ) {
							var type = jQuery.type( arg );
							if ( type === "function" ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && type !== "string" ) {
								// Inspect recursively
								add( arg );
							}
						});
					})( arguments );
					// Do we need to add the callbacks to the
					// current firing batch?
					if ( firing ) {
						firingLength = list.length;
					// With memory, if we're not firing then
					// we should call right away
					} else if ( memory ) {
						firingStart = start;
						fire( memory );
					}
				}
				return this;
			},
			// Remove a callback from the list
			remove: function() {
				if ( list ) {
					jQuery.each( arguments, function( _, arg ) {
						var index;
						while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
							list.splice( index, 1 );
							// Handle firing indexes
							if ( firing ) {
								if ( index <= firingLength ) {
									firingLength--;
								}
								if ( index <= firingIndex ) {
									firingIndex--;
								}
							}
						}
					});
				}
				return this;
			},
			// Control if a given callback is in the list
			has: function( fn ) {
				return jQuery.inArray( fn, list ) > -1;
			},
			// Remove all callbacks from the list
			empty: function() {
				list = [];
				return this;
			},
			// Have the list do nothing anymore
			disable: function() {
				list = stack = memory = undefined;
				return this;
			},
			// Is it disabled?
			disabled: function() {
				return !list;
			},
			// Lock the list in its current state
			lock: function() {
				stack = undefined;
				if ( !memory ) {
					self.disable();
				}
				return this;
			},
			// Is it locked?
			locked: function() {
				return !stack;
			},
			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				args = args || [];
				args = [ context, args.slice ? args.slice() : args ];
				if ( list && ( !fired || stack ) ) {
					if ( firing ) {
						stack.push( args );
					} else {
						fire( args );
					}
				}
				return this;
			},
			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},
			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};
jQuery.extend({

	Deferred: function( func ) {
		var tuples = [
				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks("memory") ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred(function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var action = tuple[ 0 ],
								fn = fns[ i ];
							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
								function() {
									var returned = fn.apply( this, arguments );
									if ( returned && jQuery.isFunction( returned.promise ) ) {
										returned.promise()
											.done( newDefer.resolve )
											.fail( newDefer.reject )
											.progress( newDefer.notify );
									} else {
										newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
									}
								} :
								newDefer[ action ]
							);
						});
						fns = null;
					}).promise();
				},
				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[1] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(function() {
					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
			}

			// deferred[ resolve | reject | notify ] = list.fire
			deferred[ tuple[0] ] = list.fire;
			deferred[ tuple[0] + "With" ] = list.fireWith;
		});

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = core_slice.call( arguments ),
			length = resolveValues.length,

			// the count of uncompleted subordinates
			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

			// Update function for both resolve and progress values
			updateFunc = function( i, contexts, values ) {
				return function( value ) {
					contexts[ i ] = this;
					values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
					if( values === progressValues ) {
						deferred.notifyWith( contexts, values );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( contexts, values );
					}
				};
			},

			progressValues, progressContexts, resolveContexts;

		// add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			progressValues = new Array( length );
			progressContexts = new Array( length );
			resolveContexts = new Array( length );
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject )
						.progress( updateFunc( i, progressContexts, progressValues ) );
				} else {
					--remaining;
				}
			}
		}

		// if we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( resolveContexts, resolveValues );
		}

		return deferred.promise();
	}
});
jQuery.support = (function() {

	var support,
		all,
		a,
		select,
		opt,
		input,
		fragment,
		eventName,
		i,
		isSupported,
		clickFn,
		div = document.createElement("div");

	// Setup
	div.setAttribute( "className", "t" );
	div.innerHTML = "  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";

	// Support tests won't run in some limited or non-browser environments
	all = div.getElementsByTagName("*");
	a = div.getElementsByTagName("a")[ 0 ];
	if ( !all || !a || !all.length ) {
		return {};
	}

	// First batch of tests
	select = document.createElement("select");
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName("input")[ 0 ];

	a.style.cssText = "top:1px;float:left;opacity:.5";
	support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: ( div.firstChild.nodeType === 3 ),

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName("tbody").length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName("link").length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: ( a.getAttribute("href") === "/a" ),

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.5/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: ( input.value === "on" ),

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// Tests for enctype support on a form (#6743)
		enctype: !!document.createElement("form").enctype,

		// Makes sure cloning an html5 element does not cause problems
		// Where outerHTML is undefined, this still works
		html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",

		// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
		boxModel: ( document.compatMode === "CSS1Compat" ),

		// Will be defined later
		submitBubbles: true,
		changeBubbles: true,
		focusinBubbles: false,
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true,
		boxSizingReliable: true,
		pixelPosition: false
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent( "onclick", clickFn = function() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			support.noCloneEvent = false;
		});
		div.cloneNode( true ).fireEvent("onclick");
		div.detachEvent( "onclick", clickFn );
	}

	// Check if a radio maintains its value
	// after being appended to the DOM
	input = document.createElement("input");
	input.value = "t";
	input.setAttribute( "type", "radio" );
	support.radioValue = input.value === "t";

	input.setAttribute( "checked", "checked" );

	// #11217 - WebKit loses check when the name is after the checked attribute
	input.setAttribute( "name", "t" );

	div.appendChild( input );
	fragment = document.createDocumentFragment();
	fragment.appendChild( div.lastChild );

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	fragment.removeChild( input );
	fragment.appendChild( div );

	// Technique from Juriy Zaytsev
	// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
	// We only care about the case where non-standard event systems
	// are used, namely in IE. Short-circuiting here helps us to
	// avoid an eval call (in setAttribute) which can cause CSP
	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
	if ( div.attachEvent ) {
		for ( i in {
			submit: true,
			change: true,
			focusin: true
		}) {
			eventName = "on" + i;
			isSupported = ( eventName in div );
			if ( !isSupported ) {
				div.setAttribute( eventName, "return;" );
				isSupported = ( typeof div[ eventName ] === "function" );
			}
			support[ i + "Bubbles" ] = isSupported;
		}
	}

	// Run tests that need a body at doc ready
	jQuery(function() {
		var container, div, tds, marginDiv,
			divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
			body = document.getElementsByTagName("body")[0];

		if ( !body ) {
			// Return for frameset docs that don't have a body
			return;
		}

		container = document.createElement("div");
		container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
		body.insertBefore( container, body.firstChild );

		// Construct the test element
		div = document.createElement("div");
		container.appendChild( div );

		// Check if table cells still have offsetWidth/Height when they are set
		// to display:none and there are still other visible table cells in a
		// table row; if so, offsetWidth/Height are not reliable for use when
		// determining if an element has been hidden directly using
		// display:none (it is still safe to use offsets if a parent element is
		// hidden; don safety goggles and see bug #4512 for more information).
		// (only IE 8 fails this test)
		div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
		tds = div.getElementsByTagName("td");
		tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
		isSupported = ( tds[ 0 ].offsetHeight === 0 );

		tds[ 0 ].style.display = "";
		tds[ 1 ].style.display = "none";

		// Check if empty table cells still have offsetWidth/Height
		// (IE <= 8 fail this test)
		support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );

		// Check box-sizing and margin behavior
		div.innerHTML = "";
		div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
		support.boxSizing = ( div.offsetWidth === 4 );
		support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );

		// NOTE: To any future maintainer, we've window.getComputedStyle
		// because jsdom on node.js will break without it.
		if ( window.getComputedStyle ) {
			support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
			support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";

			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. For more
			// info see bug #3333
			// Fails in WebKit before Feb 2011 nightlies
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			marginDiv = document.createElement("div");
			marginDiv.style.cssText = div.style.cssText = divReset;
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";
			div.appendChild( marginDiv );
			support.reliableMarginRight =
				!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
		}

		if ( typeof div.style.zoom !== "undefined" ) {
			// Check if natively block-level elements act like inline-block
			// elements when setting their display to 'inline' and giving
			// them layout
			// (IE < 8 does this)
			div.innerHTML = "";
			div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
			support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );

			// Check if elements with layout shrink-wrap their children
			// (IE 6 does this)
			div.style.display = "block";
			div.style.overflow = "visible";
			div.innerHTML = "<div></div>";
			div.firstChild.style.width = "5px";
			support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );

			container.style.zoom = 1;
		}

		// Null elements to avoid leaks in IE
		body.removeChild( container );
		container = div = tds = marginDiv = null;
	});

	// Null elements to avoid leaks in IE
	fragment.removeChild( div );
	all = a = select = opt = input = fragment = div = null;

	return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
	rmultiDash = /([A-Z])/g;

jQuery.extend({
	cache: {},

	deletedIds: [],

	// Remove at next major release (1.9/2.0)
	uuid: 0,

	// Unique for each copy of jQuery on the page
	// Non-digits removed to match rinlinejQuery
	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		// Ban all objects except for Flash (which handle expandos)
		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"applet": true
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var thisCache, ret,
			internalKey = jQuery.expando,
			getByName = typeof name === "string",

			// We have to handle DOM nodes and JS objects differently because IE6-7
			// can't GC object references properly across the DOM-JS boundary
			isNode = elem.nodeType,

			// Only DOM nodes need the global jQuery cache; JS object data is
			// attached directly to the object so GC can occur automatically
			cache = isNode ? jQuery.cache : elem,

			// Only defining an ID for JS objects if its cache already exists allows
			// the code to shortcut on the same path as a DOM node with no cache
			id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;

		// Avoid doing any more work than we need to when trying to get data on an
		// object that has no data at all
		if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
			return;
		}

		if ( !id ) {
			// Only DOM nodes need a new unique ID for each element since their data
			// ends up in the global cache
			if ( isNode ) {
				elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
			} else {
				id = internalKey;
			}
		}

		if ( !cache[ id ] ) {
			cache[ id ] = {};

			// Avoids exposing jQuery metadata on plain JS objects when the object
			// is serialized using JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}
		}

		// An object can be passed to jQuery.data instead of a key/value pair; this gets
		// shallow copied over onto the existing cache
		if ( typeof name === "object" || typeof name === "function" ) {
			if ( pvt ) {
				cache[ id ] = jQuery.extend( cache[ id ], name );
			} else {
				cache[ id ].data = jQuery.extend( cache[ id ].data, name );
			}
		}

		thisCache = cache[ id ];

		// jQuery data() is stored in a separate object inside the object's internal data
		// cache in order to avoid key collisions between internal data and user-defined
		// data.
		if ( !pvt ) {
			if ( !thisCache.data ) {
				thisCache.data = {};
			}

			thisCache = thisCache.data;
		}

		if ( data !== undefined ) {
			thisCache[ jQuery.camelCase( name ) ] = data;
		}

		// Check for both converted-to-camel and non-converted data property names
		// If a data property was specified
		if ( getByName ) {

			// First Try to find as-is property data
			ret = thisCache[ name ];

			// Test for null|undefined property data
			if ( ret == null ) {

				// Try to find the camelCased property
				ret = thisCache[ jQuery.camelCase( name ) ];
			}
		} else {
			ret = thisCache;
		}

		return ret;
	},

	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var thisCache, i, l,

			isNode = elem.nodeType,

			// See jQuery.data for more information
			cache = isNode ? jQuery.cache : elem,
			id = isNode ? elem[ jQuery.expando ] : jQuery.expando;

		// If there is already no cache entry for this object, there is no
		// purpose in continuing
		if ( !cache[ id ] ) {
			return;
		}

		if ( name ) {

			thisCache = pvt ? cache[ id ] : cache[ id ].data;

			if ( thisCache ) {

				// Support array or space separated string names for data keys
				if ( !jQuery.isArray( name ) ) {

					// try the string as a key before any manipulation
					if ( name in thisCache ) {
						name = [ name ];
					} else {

						// split the camel cased version by spaces unless a key with the spaces exists
						name = jQuery.camelCase( name );
						if ( name in thisCache ) {
							name = [ name ];
						} else {
							name = name.split(" ");
						}
					}
				}

				for ( i = 0, l = name.length; i < l; i++ ) {
					delete thisCache[ name[i] ];
				}

				// If there is no data left in the cache, we want to continue
				// and let the cache object itself get destroyed
				if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
					return;
				}
			}
		}

		// See jQuery.data for more information
		if ( !pvt ) {
			delete cache[ id ].data;

			// Don't destroy the parent cache unless the internal data object
			// had been the only thing left in it
			if ( !isEmptyDataObject( cache[ id ] ) ) {
				return;
			}
		}

		// Destroy the cache
		if ( isNode ) {
			jQuery.cleanData( [ elem ], true );

		// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
		} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
			delete cache[ id ];

		// When all else fails, null
		} else {
			cache[ id ] = null;
		}
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return jQuery.data( elem, name, data, true );
	},

	// A method for determining if a DOM node can handle the data expando
	acceptData: function( elem ) {
		var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];

		// nodes accept data unless otherwise specified; rejection can be conditional
		return !noData || noData !== true && elem.getAttribute("classid") === noData;
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		var parts, part, attr, name, l,
			elem = this[0],
			i = 0,
			data = null;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = jQuery.data( elem );

				if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
					attr = elem.attributes;
					for ( l = attr.length; i < l; i++ ) {
						name = attr[i].name;

						if ( !name.indexOf( "data-" ) ) {
							name = jQuery.camelCase( name.substring(5) );

							dataAttr( elem, name, data[ name ] );
						}
					}
					jQuery._data( elem, "parsedAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		parts = key.split( ".", 2 );
		parts[1] = parts[1] ? "." + parts[1] : "";
		part = parts[1] + "!";

		return jQuery.access( this, function( value ) {

			if ( value === undefined ) {
				data = this.triggerHandler( "getData" + part, [ parts[0] ] );

				// Try to fetch any internally stored data first
				if ( data === undefined && elem ) {
					data = jQuery.data( elem, key );
					data = dataAttr( elem, key, data );
				}

				return data === undefined && parts[1] ?
					this.data( parts[0] ) :
					data;
			}

			parts[1] = value;
			this.each(function() {
				var self = jQuery( this );

				self.triggerHandler( "setData" + part, parts );
				jQuery.data( this, key, value );
				self.triggerHandler( "changeData" + part, parts );
			});
		}, null, value, arguments.length > 1, null, false );
	},

	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});

function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {

		var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();

		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
				data === "false" ? false :
				data === "null" ? null :
				// Only convert to a number if it doesn't change the string
				+data + "" === data ? +data :
				rbrace.test( data ) ? jQuery.parseJSON( data ) :
					data;
			} catch( e ) {}

			// Make sure we set the data so it isn't changed later
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
	var name;
	for ( name in obj ) {

		// if the public data object is empty, the private is still empty
		if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
			continue;
		}
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}
jQuery.extend({
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = jQuery._data( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray(data) ) {
					queue = jQuery._data( elem, type, jQuery.makeArray(data) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// not intended for public consumption - generates a queueHooks object, or returns the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return jQuery._data( elem, key ) || jQuery._data( elem, key, {
			empty: jQuery.Callbacks("once memory").add(function() {
				jQuery.removeData( elem, type + "queue", true );
				jQuery.removeData( elem, key, true );
			})
		});
	}
});

jQuery.fn.extend({
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[0], type );
		}

		return data === undefined ?
			this :
			this.each(function() {
				var queue = jQuery.queue( this, type, data );

				// ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[0] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},
	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
		type = type || "fx";

		return this.queue( type, function( next, hooks ) {
			var timeout = setTimeout( next, time );
			hooks.stop = function() {
				clearTimeout( timeout );
			};
		});
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},
	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while( i-- ) {
			tmp = jQuery._data( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
});
var nodeHook, boolHook, fixSpecified,
	rclass = /[\t\r\n]/g,
	rreturn = /\r/g,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea|)$/i,
	rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
	getSetAttribute = jQuery.support.getSetAttribute;

jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each(function() {
			jQuery.removeAttr( this, name );
		});
	},

	prop: function( name, value ) {
		return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		name = jQuery.propFix[ name ] || name;
		return this.each(function() {
			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch( e ) {}
		});
	},

	addClass: function( value ) {
		var classNames, i, l, elem,
			setClass, c, cl;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).addClass( value.call(this, j, this.className) );
			});
		}

		if ( value && typeof value === "string" ) {
			classNames = value.split( core_rspace );

			for ( i = 0, l = this.length; i < l; i++ ) {
				elem = this[ i ];

				if ( elem.nodeType === 1 ) {
					if ( !elem.className && classNames.length === 1 ) {
						elem.className = value;

					} else {
						setClass = " " + elem.className + " ";

						for ( c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
								setClass += classNames[ c ] + " ";
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var removes, className, elem, c, cl, i, l;

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( j ) {
				jQuery( this ).removeClass( value.call(this, j, this.className) );
			});
		}
		if ( (value && typeof value === "string") || value === undefined ) {
			removes = ( value || "" ).split( core_rspace );

			for ( i = 0, l = this.length; i < l; i++ ) {
				elem = this[ i ];
				if ( elem.nodeType === 1 && elem.className ) {

					className = (" " + elem.className + " ").replace( rclass, " " );

					// loop over each item in the removal list
					for ( c = 0, cl = removes.length; c < cl; c++ ) {
						// Remove until there is nothing to remove,
						while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
							className = className.replace( " " + removes[ c ] + " " , " " );
						}
					}
					elem.className = value ? jQuery.trim( className ) : "";
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function( i ) {
				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					i = 0,
					self = jQuery( this ),
					state = stateVal,
					classNames = value.split( core_rspace );

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space separated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.className );
				}

				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ",
			i = 0,
			l = this.length;
		for ( ; i < l; i++ ) {
			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
				return true;
			}
		}

		return false;
	},

	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[0];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
					return ret;
				}

				ret = elem.value;

				return typeof ret === "string" ?
					// handle most common string cases
					ret.replace(rreturn, "") :
					// handle cases where value is null/undef or number
					ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each(function( i ) {
			var val,
				self = jQuery(this);

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, self.val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map(val, function ( value ) {
					return value == null ? "" : value + "";
				});
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				// attributes.value is undefined in Blackberry 4.7 but
				// uses .value. See #6932
				var val = elem.attributes.value;
				return !val || val.specified ? elem.value : elem.text;
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// oldIE doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&
							// Don't return options that are disabled or in a disabled optgroup
							( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var values = jQuery.makeArray( value );

				jQuery(elem).find("option").each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});

				if ( !values.length ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	},

	// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
	attrFn: {},

	attr: function( elem, name, value, pass ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
			return jQuery( elem )[ name ]( value );
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		// All attributes are lowercase
		// Grab necessary hook if one is defined
		if ( notxml ) {
			name = name.toLowerCase();
			hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {

			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;

			} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				elem.setAttribute( name, value + "" );
				return value;
			}

		} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
			return ret;

		} else {

			ret = elem.getAttribute( name );

			// Non-existent attributes return null, we normalize to undefined
			return ret === null ?
				undefined :
				ret;
		}
	},

	removeAttr: function( elem, value ) {
		var propName, attrNames, name, isBool,
			i = 0;

		if ( value && elem.nodeType === 1 ) {

			attrNames = value.split( core_rspace );

			for ( ; i < attrNames.length; i++ ) {
				name = attrNames[ i ];

				if ( name ) {
					propName = jQuery.propFix[ name ] || name;
					isBool = rboolean.test( name );

					// See #9699 for explanation of this approach (setting first, then removal)
					// Do not do this for boolean attributes (see #10870)
					if ( !isBool ) {
						jQuery.attr( elem, name, "" );
					}
					elem.removeAttribute( getSetAttribute ? name : propName );

					// Set corresponding property to false for boolean attributes
					if ( isBool && propName in elem ) {
						elem[ propName ] = false;
					}
				}
			}
		}
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				// We can't allow the type property to be changed (since it causes problems in IE)
				if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
					jQuery.error( "type property can't be changed" );
				} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
					// Setting the type on a radio button after the value resets the value in IE6-9
					// Reset value to it's default in case type is set after value
					// This is for element creation
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		},
		// Use the value property for back compat
		// Use the nodeHook for button elements in IE6/7 (#1954)
		value: {
			get: function( elem, name ) {
				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
					return nodeHook.get( elem, name );
				}
				return name in elem ?
					elem.value :
					null;
			},
			set: function( elem, value, name ) {
				if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
					return nodeHook.set( elem, value, name );
				}
				// Does not return so that setAttribute is also used
				elem.value = value;
			}
		}
	},

	propFix: {
		tabindex: "tabIndex",
		readonly: "readOnly",
		"for": "htmlFor",
		"class": "className",
		maxlength: "maxLength",
		cellspacing: "cellSpacing",
		cellpadding: "cellPadding",
		rowspan: "rowSpan",
		colspan: "colSpan",
		usemap: "useMap",
		frameborder: "frameBorder",
		contenteditable: "contentEditable"
	},

	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {
			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {
				return ( elem[ name ] = value );
			}

		} else {
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
				return ret;

			} else {
				return elem[ name ];
			}
		}
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				var attributeNode = elem.getAttributeNode("tabindex");

				return attributeNode && attributeNode.specified ?
					parseInt( attributeNode.value, 10 ) :
					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
						0 :
						undefined;
			}
		}
	}
});

// Hook for boolean attributes
boolHook = {
	get: function( elem, name ) {
		// Align boolean attributes with corresponding properties
		// Fall back to attribute presence where some booleans are not supported
		var attrNode,
			property = jQuery.prop( elem, name );
		return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
			name.toLowerCase() :
			undefined;
	},
	set: function( elem, value, name ) {
		var propName;
		if ( value === false ) {
			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			// value is true since we know at this point it's type boolean and not false
			// Set boolean attributes to the same name and set the DOM property
			propName = jQuery.propFix[ name ] || name;
			if ( propName in elem ) {
				// Only set the IDL specifically if it already exists on the element
				elem[ propName ] = true;
			}

			elem.setAttribute( name, name.toLowerCase() );
		}
		return name;
	}
};

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

	fixSpecified = {
		name: true,
		id: true,
		coords: true
	};

	// Use this for any attribute in IE6/7
	// This fixes almost every IE6/7 issue
	nodeHook = jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret;
			ret = elem.getAttributeNode( name );
			return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
				ret.value :
				undefined;
		},
		set: function( elem, value, name ) {
			// Set the existing or create a new attribute node
			var ret = elem.getAttributeNode( name );
			if ( !ret ) {
				ret = document.createAttribute( name );
				elem.setAttributeNode( ret );
			}
			return ( ret.value = value + "" );
		}
	};

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each([ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		});
	});

	// Set contenteditable to false on removals(#10429)
	// Setting to empty string throws an error as an invalid value
	jQuery.attrHooks.contenteditable = {
		get: nodeHook.get,
		set: function( elem, value, name ) {
			if ( value === "" ) {
				value = "false";
			}
			nodeHook.set( elem, value, name );
		}
	};
}


// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			get: function( elem ) {
				var ret = elem.getAttribute( name, 2 );
				return ret === null ? undefined : ret;
			}
		});
	});
}

if ( !jQuery.support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {
			// Return undefined in the case of empty string
			// Normalize to lowercase since IE uppercases css property names
			return elem.style.cssText.toLowerCase() || undefined;
		},
		set: function( elem, value ) {
			return ( elem.style.cssText = value + "" );
		}
	};
}

// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
			return null;
		}
	});
}

// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
	jQuery.propFix.enctype = "encoding";
}

// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
	jQuery.each([ "radio", "checkbox" ], function() {
		jQuery.valHooks[ this ] = {
			get: function( elem ) {
				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				return elem.getAttribute("value") === null ? "on" : elem.value;
			}
		};
	});
}
jQuery.each([ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
			}
		}
	});
});
var rformElems = /^(?:textarea|input|select)$/i,
	rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
	rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|contextmenu)|click/,
	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	hoverHack = function( events ) {
		return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
	};

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	add: function( elem, types, handler, data, selector ) {

		var elemData, eventHandle, events,
			t, tns, type, namespaces, handleObj,
			handleObjIn, handlers, special;

		// Don't attach events to noData or text/comment nodes (allow plain objects tho)
		if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		events = elemData.events;
		if ( !events ) {
			elemData.events = events = {};
		}
		eventHandle = elemData.handle;
		if ( !eventHandle ) {
			elemData.handle = eventHandle = function( e ) {
				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
					undefined;
			};
			// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
			eventHandle.elem = elem;
		}

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = jQuery.trim( hoverHack(types) ).split( " " );
		for ( t = 0; t < types.length; t++ ) {

			tns = rtypenamespace.exec( types[t] ) || [];
			type = tns[1];
			namespaces = ( tns[2] || "" ).split( "." ).sort();

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend({
				type: type,
				origType: tns[1],
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join(".")
			}, handleObjIn );

			// Init the event handler queue if we're the first
			handlers = events[ type ];
			if ( !handlers ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener/attachEvent if the special events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	global: {},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var t, tns, type, origType, namespaces, origCount,
			j, events, special, eventType, handleObj,
			elemData = jQuery.hasData( elem ) && jQuery._data( elem );

		if ( !elemData || !(events = elemData.events) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
		for ( t = 0; t < types.length; t++ ) {
			tns = rtypenamespace.exec( types[t] ) || [];
			type = origType = tns[1];
			namespaces = tns[2];

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector? special.delegateType : special.bindType ) || type;
			eventType = events[ type ] || [];
			origCount = eventType.length;
			namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;

			// Remove matching events
			for ( j = 0; j < eventType.length; j++ ) {
				handleObj = eventType[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					 ( !handler || handler.guid === handleObj.guid ) &&
					 ( !namespaces || namespaces.test( handleObj.namespace ) ) &&
					 ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
					eventType.splice( j--, 1 );

					if ( handleObj.selector ) {
						eventType.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( eventType.length === 0 && origCount !== eventType.length ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			delete elemData.handle;

			// removeData also checks for emptiness and clears the expando if empty
			// so use it instead of delete
			jQuery.removeData( elem, "events", true );
		}
	},

	// Events that are safe to short-circuit if no handlers are attached.
	// Native DOM events should not be added, they may have inline handlers.
	customEvent: {
		"getData": true,
		"setData": true,
		"changeData": true
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		// Don't do events on text and comment nodes
		if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
			return;
		}

		// Event object or event type
		var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
			type = event.type || event,
			namespaces = [];

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "!" ) >= 0 ) {
			// Exclusive events trigger only for the exact event (no namespaces)
			type = type.slice(0, -1);
			exclusive = true;
		}

		if ( type.indexOf( "." ) >= 0 ) {
			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split(".");
			type = namespaces.shift();
			namespaces.sort();
		}

		if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
			// No jQuery handlers for this event type, and it can't have inline handlers
			return;
		}

		// Caller can pass in an Event, Object, or just an event type string
		event = typeof event === "object" ?
			// jQuery.Event object
			event[ jQuery.expando ] ? event :
			// Object literal
			new jQuery.Event( type, event ) :
			// Just the event type (string)
			new jQuery.Event( type );

		event.type = type;
		event.isTrigger = true;
		event.exclusive = exclusive;
		event.namespace = namespaces.join( "." );
		event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
		ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";

		// Handle a global trigger
		if ( !elem ) {

			// TODO: Stop taunting the data cache; remove global events and always attach to document
			cache = jQuery.cache;
			for ( i in cache ) {
				if ( cache[ i ].events && cache[ i ].events[ type ] ) {
					jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
				}
			}
			return;
		}

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data != null ? jQuery.makeArray( data ) : [];
		data.unshift( event );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		eventPath = [[ elem, special.bindType || type ]];
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
			for ( old = elem; cur; cur = cur.parentNode ) {
				eventPath.push([ cur, bubbleType ]);
				old = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( old === (elem.ownerDocument || document) ) {
				eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
			}
		}

		// Fire handlers on the event path
		for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {

			cur = eventPath[i][0];
			event.type = eventPath[i][1];

			handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}
			// Note that this is a bare JS function and not a jQuery handler
			handle = ontype && cur[ ontype ];
			if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
				event.preventDefault();
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name name as the event.
				// Can't use an .isFunction() check here because IE6/7 fails that test.
				// Don't do default actions on window, that's where global variables be (#6170)
				// IE<9 dies on focus/blur to hidden element (#1486)
				if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					old = elem[ ontype ];

					if ( old ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					elem[ type ]();
					jQuery.event.triggered = undefined;

					if ( old ) {
						elem[ ontype ] = old;
					}
				}
			}
		}

		return event.result;
	},

	dispatch: function( event ) {

		// Make a writable jQuery.Event from the native event object
		event = jQuery.event.fix( event || window.event );

		var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
			handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
			delegateCount = handlers.delegateCount,
			args = core_slice.call( arguments ),
			run_all = !event.exclusive && !event.namespace,
			special = jQuery.event.special[ event.type ] || {},
			handlerQueue = [];

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[0] = event;
		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers that should run if there are delegated events
		// Avoid non-left-click bubbling in Firefox (#3861)
		if ( delegateCount && !(event.button && event.type === "click") ) {

			for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {

				// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.disabled !== true || event.type !== "click" ) {
					selMatch = {};
					matches = [];
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];
						sel = handleObj.selector;

						if ( selMatch[ sel ] === undefined ) {
							selMatch[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) >= 0 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( selMatch[ sel ] ) {
							matches.push( handleObj );
						}
					}
					if ( matches.length ) {
						handlerQueue.push({ elem: cur, matches: matches });
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		if ( handlers.length > delegateCount ) {
			handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
		}

		// Run delegates first; they may want to stop propagation beneath us
		for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
			matched = handlerQueue[ i ];
			event.currentTarget = matched.elem;

			for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
				handleObj = matched.matches[ j ];

				// Triggered event must either 1) be non-exclusive and have no namespace, or
				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
				if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {

					event.data = handleObj.data;
					event.handleObj = handleObj;

					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
							.apply( matched.elem, args );

					if ( ret !== undefined ) {
						event.result = ret;
						if ( ret === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	// Includes some event props shared by KeyEvent and MouseEvent
	// *** attrChange attrName relatedNode srcElement  are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
	props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),

	fixHooks: {},

	keyHooks: {
		props: "char charCode key keyCode".split(" "),
		filter: function( event, original ) {

			// Add which for key events
			if ( event.which == null ) {
				event.which = original.charCode != null ? original.charCode : original.keyCode;
			}

			return event;
		}
	},

	mouseHooks: {
		props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
		filter: function( event, original ) {
			var eventDoc, doc, body,
				button = original.button,
				fromElement = original.fromElement;

			// Calculate pageX/Y if missing and clientX/Y available
			if ( event.pageX == null && original.clientX != null ) {
				eventDoc = event.target.ownerDocument || document;
				doc = eventDoc.documentElement;
				body = eventDoc.body;

				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
			}

			// Add relatedTarget, if necessary
			if ( !event.relatedTarget && fromElement ) {
				event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			// Note: button is not normalized, so don't use it
			if ( !event.which && button !== undefined ) {
				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
			}

			return event;
		}
	},

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// Create a writable copy of the event object and normalize some properties
		var i, prop,
			originalEvent = event,
			fixHook = jQuery.event.fixHooks[ event.type ] || {},
			copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;

		event = jQuery.Event( originalEvent );

		for ( i = copy.length; i; ) {
			prop = copy[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
		if ( !event.target ) {
			event.target = originalEvent.srcElement || document;
		}

		// Target should not be a text node (#504, Safari)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
		event.metaKey = !!event.metaKey;

		return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
	},

	special: {
		load: {
			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},

		focus: {
			delegateType: "focusin"
		},
		blur: {
			delegateType: "focusout"
		},

		beforeunload: {
			setup: function( data, namespaces, eventHandle ) {
				// We only want to do this special case on windows
				if ( jQuery.isWindow( this ) ) {
					this.onbeforeunload = eventHandle;
				}
			},

			teardown: function( namespaces, eventHandle ) {
				if ( this.onbeforeunload === eventHandle ) {
					this.onbeforeunload = null;
				}
			}
		}
	},

	simulate: function( type, elem, event, bubble ) {
		// Piggyback on a donor event to simulate a different one.
		// Fake originalEvent to avoid donor's stopPropagation, but if the
		// simulated event prevents default then we do the same on the donor.
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{ type: type,
				isSimulated: true,
				originalEvent: {}
			}
		);
		if ( bubble ) {
			jQuery.event.trigger( e, null, elem );
		} else {
			jQuery.event.dispatch.call( elem, e );
		}
		if ( e.isDefaultPrevented() ) {
			event.preventDefault();
		}
	}
};

// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		var name = "on" + type;

		if ( elem.detachEvent ) {

			// #8545, #7054, preventing memory leaks for custom events in IE6-8
			// detachEvent needed property on element, by name of that event, to properly expose it to GC
			if ( typeof elem[ name ] === "undefined" ) {
				elem[ name ] = null;
			}

			elem.detachEvent( name, handle );
		}
	};

jQuery.Event = function( src, props ) {
	// Allow instantiation without the 'new' keyword
	if ( !(this instanceof jQuery.Event) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
			src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

function returnFalse() {
	return false;
}
function returnTrue() {
	return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}

		// if preventDefault exists run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// otherwise set the returnValue property of the original event to false (IE)
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if stopPropagation exists run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};

// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj,
				selector = handleObj.selector;

			// For mousenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
});

// IE submit delegation
if ( !jQuery.support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Lazy-add a submit handler when a descendant form may potentially be submitted
			jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
				// Node name check avoids a VML-related crash in IE (#9807)
				var elem = e.target,
					form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
				if ( form && !jQuery._data( form, "_submit_attached" ) ) {
					jQuery.event.add( form, "submit._submit", function( event ) {
						event._submit_bubble = true;
					});
					jQuery._data( form, "_submit_attached", true );
				}
			});
			// return undefined since we don't need an event listener
		},

		postDispatch: function( event ) {
			// If form was submitted by the user, bubble the event up the tree
			if ( event._submit_bubble ) {
				delete event._submit_bubble;
				if ( this.parentNode && !event.isTrigger ) {
					jQuery.event.simulate( "submit", this.parentNode, event, true );
				}
			}
		},

		teardown: function() {
			// Only need this for delegated form submit events
			if ( jQuery.nodeName( this, "form" ) ) {
				return false;
			}

			// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
			jQuery.event.remove( this, "._submit" );
		}
	};
}

// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {

	jQuery.event.special.change = {

		setup: function() {

			if ( rformElems.test( this.nodeName ) ) {
				// IE doesn't fire change on a check/radio until blur; trigger it on click
				// after a propertychange. Eat the blur-change in special.change.handle.
				// This still fires onchange a second time for check/radio after blur.
				if ( this.type === "checkbox" || this.type === "radio" ) {
					jQuery.event.add( this, "propertychange._change", function( event ) {
						if ( event.originalEvent.propertyName === "checked" ) {
							this._just_changed = true;
						}
					});
					jQuery.event.add( this, "click._change", function( event ) {
						if ( this._just_changed && !event.isTrigger ) {
							this._just_changed = false;
						}
						// Allow triggered, simulated change events (#11500)
						jQuery.event.simulate( "change", this, event, true );
					});
				}
				return false;
			}
			// Delegated event; lazy-add a change handler on descendant inputs
			jQuery.event.add( this, "beforeactivate._change", function( e ) {
				var elem = e.target;

				if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
					jQuery.event.add( elem, "change._change", function( event ) {
						if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
							jQuery.event.simulate( "change", this.parentNode, event, true );
						}
					});
					jQuery._data( elem, "_change_attached", true );
				}
			});
		},

		handle: function( event ) {
			var elem = event.target;

			// Swallow native change events from checkbox/radio, we already triggered them above
			if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
				return event.handleObj.handler.apply( this, arguments );
			}
		},

		teardown: function() {
			jQuery.event.remove( this, "._change" );

			return !rformElems.test( this.nodeName );
		}
	};
}

// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler while someone wants focusin/focusout
		var attaches = 0,
			handler = function( event ) {
				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
			};

		jQuery.event.special[ fix ] = {
			setup: function() {
				if ( attaches++ === 0 ) {
					document.addEventListener( orig, handler, true );
				}
			},
			teardown: function() {
				if ( --attaches === 0 ) {
					document.removeEventListener( orig, handler, true );
				}
			}
		};
	});
}

jQuery.fn.extend({

	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
		var origFn, type;

		// Types can be a map of types/handlers
		if ( typeof types === "object" ) {
			// ( types-Object, selector, data )
			if ( typeof selector !== "string" ) { // && selector != null
				// ( types-Object, data )
				data = data || selector;
				selector = undefined;
			}
			for ( type in types ) {
				this.on( type, selector, data, types[ type ], one );
			}
			return this;
		}

		if ( data == null && fn == null ) {
			// ( types, fn )
			fn = selector;
			data = selector = undefined;
		} else if ( fn == null ) {
			if ( typeof selector === "string" ) {
				// ( types, selector, fn )
				fn = data;
				data = undefined;
			} else {
				// ( types, data, fn )
				fn = data;
				data = selector;
				selector = undefined;
			}
		}
		if ( fn === false ) {
			fn = returnFalse;
		} else if ( !fn ) {
			return this;
		}

		if ( one === 1 ) {
			origFn = fn;
			fn = function( event ) {
				// Can use an empty set, since event contains the info
				jQuery().off( event );
				return origFn.apply( this, arguments );
			};
			// Use same guid so caller can remove using origFn
			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
		}
		return this.each( function() {
			jQuery.event.add( this, types, fn, data, selector );
		});
	},
	one: function( types, selector, data, fn ) {
		return this.on( types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {
			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {
			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {
			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each(function() {
			jQuery.event.remove( this, types, fn, selector );
		});
	},

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	live: function( types, data, fn ) {
		jQuery( this.context ).on( types, this.selector, data, fn );
		return this;
	},
	die: function( types, fn ) {
		jQuery( this.context ).off( types, this.selector || "**", fn );
		return this;
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {
		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
	},

	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},
	triggerHandler: function( type, data ) {
		if ( this[0] ) {
			return jQuery.event.trigger( type, data, this[0], true );
		}
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments,
			guid = fn.guid || jQuery.guid++,
			i = 0,
			toggler = function( event ) {
				// Figure out which function to execute
				var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
				jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );

				// Make sure that clicks stop
				event.preventDefault();

				// and execute the function
				return args[ lastToggle ].apply( this, arguments ) || false;
			};

		// link all the functions, so any of them can unbind this click handler
		toggler.guid = guid;
		while ( i < args.length ) {
			args[ i++ ].guid = guid;
		}

		return this.click( toggler );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
});

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		if ( fn == null ) {
			fn = data;
			data = null;
		}

		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};

	if ( rkeyEvent.test( name ) ) {
		jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
	}

	if ( rmouseEvent.test( name ) ) {
		jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
	}
});
/*!
 * Sizzle CSS Selector Engine
 * Copyright 2012 jQuery Foundation and other contributors
 * Released under the MIT license
 * http://sizzlejs.com/
 */
(function( window, undefined ) {

var cachedruns,
	assertGetIdNotName,
	Expr,
	getText,
	isXML,
	contains,
	compile,
	sortOrder,
	hasDuplicate,
	outermostContext,

	baseHasDuplicate = true,
	strundefined = "undefined",

	expando = ( "sizcache" + Math.random() ).replace( ".", "" ),

	Token = String,
	document = window.document,
	docElem = document.documentElement,
	dirruns = 0,
	done = 0,
	pop = [].pop,
	push = [].push,
	slice = [].slice,
	// Use a stripped-down indexOf if a native one is unavailable
	indexOf = [].indexOf || function( elem ) {
		var i = 0,
			len = this.length;
		for ( ; i < len; i++ ) {
			if ( this[i] === elem ) {
				return i;
			}
		}
		return -1;
	},

	// Augment a function for special use by Sizzle
	markFunction = function( fn, value ) {
		fn[ expando ] = value == null || value;
		return fn;
	},

	createCache = function() {
		var cache = {},
			keys = [];

		return markFunction(function( key, value ) {
			// Only keep the most recent entries
			if ( keys.push( key ) > Expr.cacheLength ) {
				delete cache[ keys.shift() ];
			}

			// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
			return (cache[ key + " " ] = value);
		}, cache );
	},

	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),

	// Regex

	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",
	// http://www.w3.org/TR/css3-syntax/#characters
	characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",

	// Loosely modeled on CSS identifier characters
	// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = characterEncoding.replace( "w", "w#" ),

	// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
	operators = "([*^$|!~]?=)",
	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
		"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",

	// Prefer arguments not in parens/brackets,
	//   then attribute selectors and non-pseudos (denoted by :),
	//   then anything else
	// These preferences are here to reduce the number of selectors
	//   needing tokenize in the PSEUDO preFilter
	pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",

	// For matchExpr.POS and matchExpr.needsContext
	pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
		"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
	rpseudo = new RegExp( pseudos ),

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,

	rnot = /^:not/,
	rsibling = /[\x20\t\r\n\f]*[+~]/,
	rendsWithNot = /:not\($/,

	rheader = /h\d/i,
	rinputs = /input|select|textarea|button/i,

	rbackslash = /\\(?!\\)/g,

	matchExpr = {
		"ID": new RegExp( "^#(" + characterEncoding + ")" ),
		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
		"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"POS": new RegExp( pos, "i" ),
		"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		// For use in libraries implementing .is()
		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
	},

	// Support

	// Used for testing something on an element
	assert = function( fn ) {
		var div = document.createElement("div");

		try {
			return fn( div );
		} catch (e) {
			return false;
		} finally {
			// release memory in IE
			div = null;
		}
	},

	// Check if getElementsByTagName("*") returns only elements
	assertTagNameNoComments = assert(function( div ) {
		div.appendChild( document.createComment("") );
		return !div.getElementsByTagName("*").length;
	}),

	// Check if getAttribute returns normalized href attributes
	assertHrefNotNormalized = assert(function( div ) {
		div.innerHTML = "<a href='#'></a>";
		return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
			div.firstChild.getAttribute("href") === "#";
	}),

	// Check if attributes should be retrieved by attribute nodes
	assertAttributes = assert(function( div ) {
		div.innerHTML = "<select></select>";
		var type = typeof div.lastChild.getAttribute("multiple");
		// IE8 returns a string for some attributes even when not present
		return type !== "boolean" && type !== "string";
	}),

	// Check if getElementsByClassName can be trusted
	assertUsableClassName = assert(function( div ) {
		// Opera can't find a second classname (in 9.6)
		div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
		if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
			return false;
		}

		// Safari 3.2 caches class attributes and doesn't catch changes
		div.lastChild.className = "e";
		return div.getElementsByClassName("e").length === 2;
	}),

	// Check if getElementById returns elements by name
	// Check if getElementsByName privileges form controls or returns elements by ID
	assertUsableName = assert(function( div ) {
		// Inject content
		div.id = expando + 0;
		div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
		docElem.insertBefore( div, docElem.firstChild );

		// Test
		var pass = document.getElementsByName &&
			// buggy browsers will return fewer than the correct 2
			document.getElementsByName( expando ).length === 2 +
			// buggy browsers will return more than the correct 0
			document.getElementsByName( expando + 0 ).length;
		assertGetIdNotName = !document.getElementById( expando );

		// Cleanup
		docElem.removeChild( div );

		return pass;
	});

// If slice is not available, provide a backup
try {
	slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
	slice = function( i ) {
		var elem,
			results = [];
		for ( ; (elem = this[i]); i++ ) {
			results.push( elem );
		}
		return results;
	};
}

function Sizzle( selector, context, results, seed ) {
	results = results || [];
	context = context || document;
	var match, elem, xml, m,
		nodeType = context.nodeType;

	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	if ( nodeType !== 1 && nodeType !== 9 ) {
		return [];
	}

	xml = isXML( context );

	if ( !xml && !seed ) {
		if ( (match = rquickExpr.exec( selector )) ) {
			// Speed-up: Sizzle("#ID")
			if ( (m = match[1]) ) {
				if ( nodeType === 9 ) {
					elem = context.getElementById( m );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE, Opera, and Webkit return items
						// by name instead of ID
						if ( elem.id === m ) {
							results.push( elem );
							return results;
						}
					} else {
						return results;
					}
				} else {
					// Context is not a document
					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
						contains( context, elem ) && elem.id === m ) {
						results.push( elem );
						return results;
					}
				}

			// Speed-up: Sizzle("TAG")
			} else if ( match[2] ) {
				push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
				return results;

			// Speed-up: Sizzle(".CLASS")
			} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
				push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
				return results;
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	return Sizzle( expr, null, null, [ elem ] ).length > 0;
};

// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return (name === "input" || name === "button") && elem.type === type;
	};
}

// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
	return markFunction(function( argument ) {
		argument = +argument;
		return markFunction(function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ (j = matchIndexes[i]) ] ) {
					seed[j] = !(matches[j] = seed[j]);
				}
			}
		});
	});
}

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( nodeType ) {
		if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
			// Use textContent for elements
			// innerText usage removed for consistency of new lines (see #11153)
			if ( typeof elem.textContent === "string" ) {
				return elem.textContent;
			} else {
				// Traverse its children
				for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
					ret += getText( elem );
				}
			}
		} else if ( nodeType === 3 || nodeType === 4 ) {
			return elem.nodeValue;
		}
		// Do not include comment or processing instruction nodes
	} else {

		// If no nodeType, this is expected to be an array
		for ( ; (node = elem[i]); i++ ) {
			// Do not traverse comment nodes
			ret += getText( node );
		}
	}
	return ret;
};

isXML = Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

// Element contains another
contains = Sizzle.contains = docElem.contains ?
	function( a, b ) {
		var adown = a.nodeType === 9 ? a.documentElement : a,
			bup = b && b.parentNode;
		return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
	} :
	docElem.compareDocumentPosition ?
	function( a, b ) {
		return b && !!( a.compareDocumentPosition( b ) & 16 );
	} :
	function( a, b ) {
		while ( (b = b.parentNode) ) {
			if ( b === a ) {
				return true;
			}
		}
		return false;
	};

Sizzle.attr = function( elem, name ) {
	var val,
		xml = isXML( elem );

	if ( !xml ) {
		name = name.toLowerCase();
	}
	if ( (val = Expr.attrHandle[ name ]) ) {
		return val( elem );
	}
	if ( xml || assertAttributes ) {
		return elem.getAttribute( name );
	}
	val = elem.getAttributeNode( name );
	return val ?
		typeof elem[ name ] === "boolean" ?
			elem[ name ] ? name : null :
			val.specified ? val.value : null :
		null;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	// IE6/7 return a modified href
	attrHandle: assertHrefNotNormalized ?
		{} :
		{
			"href": function( elem ) {
				return elem.getAttribute( "href", 2 );
			},
			"type": function( elem ) {
				return elem.getAttribute("type");
			}
		},

	find: {
		"ID": assertGetIdNotName ?
			function( id, context, xml ) {
				if ( typeof context.getElementById !== strundefined && !xml ) {
					var m = context.getElementById( id );
					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					return m && m.parentNode ? [m] : [];
				}
			} :
			function( id, context, xml ) {
				if ( typeof context.getElementById !== strundefined && !xml ) {
					var m = context.getElementById( id );

					return m ?
						m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
							[m] :
							undefined :
						[];
				}
			},

		"TAG": assertTagNameNoComments ?
			function( tag, context ) {
				if ( typeof context.getElementsByTagName !== strundefined ) {
					return context.getElementsByTagName( tag );
				}
			} :
			function( tag, context ) {
				var results = context.getElementsByTagName( tag );

				// Filter out possible comments
				if ( tag === "*" ) {
					var elem,
						tmp = [],
						i = 0;

					for ( ; (elem = results[i]); i++ ) {
						if ( elem.nodeType === 1 ) {
							tmp.push( elem );
						}
					}

					return tmp;
				}
				return results;
			},

		"NAME": assertUsableName && function( tag, context ) {
			if ( typeof context.getElementsByName !== strundefined ) {
				return context.getElementsByName( name );
			}
		},

		"CLASS": assertUsableClassName && function( className, context, xml ) {
			if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
				return context.getElementsByClassName( className );
			}
		}
	},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[1] = match[1].replace( rbackslash, "" );

			// Move the given value to match[3] whether quoted or unquoted
			match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );

			if ( match[2] === "~=" ) {
				match[3] = " " + match[3] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {
			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				3 xn-component of xn+y argument ([+-]?\d*n|)
				4 sign of xn-component
				5 x of xn-component
				6 sign of y-component
				7 y of y-component
			*/
			match[1] = match[1].toLowerCase();

			if ( match[1] === "nth" ) {
				// nth-child requires argument
				if ( !match[2] ) {
					Sizzle.error( match[0] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
				match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );

			// other types prohibit arguments
			} else if ( match[2] ) {
				Sizzle.error( match[0] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var unquoted, excess;
			if ( matchExpr["CHILD"].test( match[0] ) ) {
				return null;
			}

			if ( match[3] ) {
				match[2] = match[3];
			} else if ( (unquoted = match[4]) ) {
				// Only check arguments that contain a pseudo
				if ( rpseudo.test(unquoted) &&
					// Get excess from tokenize (recursively)
					(excess = tokenize( unquoted, true )) &&
					// advance to the next closing parenthesis
					(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {

					// excess is a negative index
					unquoted = unquoted.slice( 0, excess );
					match[0] = match[0].slice( 0, excess );
				}
				match[2] = unquoted;
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {
		"ID": assertGetIdNotName ?
			function( id ) {
				id = id.replace( rbackslash, "" );
				return function( elem ) {
					return elem.getAttribute("id") === id;
				};
			} :
			function( id ) {
				id = id.replace( rbackslash, "" );
				return function( elem ) {
					var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
					return node && node.value === id;
				};
			},

		"TAG": function( nodeName ) {
			if ( nodeName === "*" ) {
				return function() { return true; };
			}
			nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();

			return function( elem ) {
				return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
			};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ expando ][ className + " " ];

			return pattern ||
				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
				classCache( className, function( elem ) {
					return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
				});
		},

		"ATTR": function( name, operator, check ) {
			return function( elem, context ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.substr( result.length - check.length ) === check :
					operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
					false;
			};
		},

		"CHILD": function( type, argument, first, last ) {

			if ( type === "nth" ) {
				return function( elem ) {
					var node, diff,
						parent = elem.parentNode;

					if ( first === 1 && last === 0 ) {
						return true;
					}

					if ( parent ) {
						diff = 0;
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								diff++;
								if ( elem === node ) {
									break;
								}
							}
						}
					}

					// Incorporate the offset (or cast to NaN), then check against cycle size
					diff -= last;
					return diff === first || ( diff % first === 0 && diff / first >= 0 );
				};
			}

			return function( elem ) {
				var node = elem;

				switch ( type ) {
					case "only":
					case "first":
						while ( (node = node.previousSibling) ) {
							if ( node.nodeType === 1 ) {
								return false;
							}
						}

						if ( type === "first" ) {
							return true;
						}

						node = elem;

						/* falls through */
					case "last":
						while ( (node = node.nextSibling) ) {
							if ( node.nodeType === 1 ) {
								return false;
							}
						}

						return true;
				}
			};
		},

		"PSEUDO": function( pseudo, argument ) {
			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction(function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf.call( seed, matched[i] );
							seed[ idx ] = !( matches[ idx ] = matched[i] );
						}
					}) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {
		"not": markFunction(function( selector ) {
			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction(function( seed, matches, context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( (elem = unmatched[i]) ) {
							seed[i] = !(matches[i] = elem);
						}
					}
				}) :
				function( elem, context, xml ) {
					input[0] = elem;
					matcher( input, null, xml, results );
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			return function( elem ) {
				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
			};
		}),

		"enabled": function( elem ) {
			return elem.disabled === false;
		},

		"disabled": function( elem ) {
			return elem.disabled === true;
		},

		"checked": function( elem ) {
			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
		},

		"selected": function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos["empty"]( elem );
		},

		"empty": function( elem ) {
			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
			//   not comment, processing instructions, or others
			// Thanks to Diego Perini for the nodeName shortcut
			//   Greater than "@" means alpha characters (specifically not starting with "#" or "?")
			var nodeType;
			elem = elem.firstChild;
			while ( elem ) {
				if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
					return false;
				}
				elem = elem.nextSibling;
			}
			return true;
		},

		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"text": function( elem ) {
			var type, attr;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
			// use getAttribute instead to test this case
			return elem.nodeName.toLowerCase() === "input" &&
				(type = elem.type) === "text" &&
				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
		},

		// Input types
		"radio": createInputPseudo("radio"),
		"checkbox": createInputPseudo("checkbox"),
		"file": createInputPseudo("file"),
		"password": createInputPseudo("password"),
		"image": createInputPseudo("image"),

		"submit": createButtonPseudo("submit"),
		"reset": createButtonPseudo("reset"),

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"focus": function( elem ) {
			var doc = elem.ownerDocument;
			return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
		},

		"active": function( elem ) {
			return elem === elem.ownerDocument.activeElement;
		},

		// Positional types
		"first": createPositionalPseudo(function() {
			return [ 0 ];
		}),

		"last": createPositionalPseudo(function( matchIndexes, length ) {
			return [ length - 1 ];
		}),

		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		}),

		"even": createPositionalPseudo(function( matchIndexes, length ) {
			for ( var i = 0; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"odd": createPositionalPseudo(function( matchIndexes, length ) {
			for ( var i = 1; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		})
	}
};

function siblingCheck( a, b, ret ) {
	if ( a === b ) {
		return ret;
	}

	var cur = a.nextSibling;

	while ( cur ) {
		if ( cur === b ) {
			return -1;
		}

		cur = cur.nextSibling;
	}

	return 1;
}

sortOrder = docElem.compareDocumentPosition ?
	function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
			a.compareDocumentPosition :
			a.compareDocumentPosition(b) & 4
		) ? -1 : 1;
	} :
	function( a, b ) {
		// The nodes are identical, we can exit early
		if ( a === b ) {
			hasDuplicate = true;
			return 0;

		// Fallback to using sourceIndex (in IE) if it's available on both nodes
		} else if ( a.sourceIndex && b.sourceIndex ) {
			return a.sourceIndex - b.sourceIndex;
		}

		var al, bl,
			ap = [],
			bp = [],
			aup = a.parentNode,
			bup = b.parentNode,
			cur = aup;

		// If the nodes are siblings (or identical) we can do a quick check
		if ( aup === bup ) {
			return siblingCheck( a, b );

		// If no parents were found then the nodes are disconnected
		} else if ( !aup ) {
			return -1;

		} else if ( !bup ) {
			return 1;
		}

		// Otherwise they're somewhere else in the tree so we need
		// to build up a full list of the parentNodes for comparison
		while ( cur ) {
			ap.unshift( cur );
			cur = cur.parentNode;
		}

		cur = bup;

		while ( cur ) {
			bp.unshift( cur );
			cur = cur.parentNode;
		}

		al = ap.length;
		bl = bp.length;

		// Start walking down the tree looking for a discrepancy
		for ( var i = 0; i < al && i < bl; i++ ) {
			if ( ap[i] !== bp[i] ) {
				return siblingCheck( ap[i], bp[i] );
			}
		}

		// We ended someplace up the tree so do a sibling check
		return i === al ?
			siblingCheck( a, bp[i], -1 ) :
			siblingCheck( ap[i], b, 1 );
	};

// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;

// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		i = 1,
		j = 0;

	hasDuplicate = baseHasDuplicate;
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		for ( ; (elem = results[i]); i++ ) {
			if ( elem === results[ i - 1 ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	return results;
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

function tokenize( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ expando ][ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || (match = rcomma.exec( soFar )) ) {
			if ( match ) {
				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[0].length ) || soFar;
			}
			groups.push( tokens = [] );
		}

		matched = false;

		// Combinators
		if ( (match = rcombinators.exec( soFar )) ) {
			tokens.push( matched = new Token( match.shift() ) );
			soFar = soFar.slice( matched.length );

			// Cast descendant combinators to space
			matched.type = match[0].replace( rtrim, " " );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
				(match = preFilters[ type ]( match ))) ) {

				tokens.push( matched = new Token( match.shift() ) );
				soFar = soFar.slice( matched.length );
				matched.type = type;
				matched.matches = match;
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :
			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		checkNonElements = base && combinator.dir === "parentNode",
		doneName = done++;

	return combinator.first ?
		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( (elem = elem[ dir ]) ) {
				if ( checkNonElements || elem.nodeType === 1  ) {
					return matcher( elem, context, xml );
				}
			}
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
			if ( !xml ) {
				var cache,
					dirkey = dirruns + " " + doneName + " ",
					cachedkey = dirkey + cachedruns;
				while ( (elem = elem[ dir ]) ) {
					if ( checkNonElements || elem.nodeType === 1 ) {
						if ( (cache = elem[ expando ]) === cachedkey ) {
							return elem.sizset;
						} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
							if ( elem.sizset ) {
								return elem;
							}
						} else {
							elem[ expando ] = cachedkey;
							if ( matcher( elem, context, xml ) ) {
								elem.sizset = true;
								return elem;
							}
							elem.sizset = false;
						}
					}
				}
			} else {
				while ( (elem = elem[ dir ]) ) {
					if ( checkNonElements || elem.nodeType === 1 ) {
						if ( matcher( elem, context, xml ) ) {
							return elem;
						}
					}
				}
			}
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[i]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[0];
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( (elem = unmatched[i]) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction(function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( (elem = temp[i]) ) {
					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {
					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( (elem = matcherOut[i]) ) {
							// Restore matcherIn since elem is not yet a final match
							temp.push( (matcherIn[i] = elem) );
						}
					}
					postFinder( null, (matcherOut = []), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( (elem = matcherOut[i]) &&
						(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {

						seed[temp] = !(results[temp] = elem);
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	});
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[0].type ],
		implicitRelative = leadingRelative || Expr.relative[" "],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf.call( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
		} ];

	for ( ; i < len; i++ ) {
		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
			matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
		} else {
			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {
				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[j].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
					j < len && tokens.join("")
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, expandContext ) {
			var elem, j, matcher,
				setMatched = [],
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				outermost = expandContext != null,
				contextBackup = outermostContext,
				// We must always have either seed elements or context
				elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
				// Nested matchers should use non-integer dirruns
				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);

			if ( outermost ) {
				outermostContext = context !== document && context;
				cachedruns = superMatcher.el;
			}

			// Add elements passing elementMatchers directly to results
			for ( ; (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
						if ( matcher( elem, context, xml ) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
						cachedruns = ++superMatcher.el;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// Apply set filters to unmatched elements
			matchedCount += i;
			if ( bySet && i !== matchedCount ) {
				for ( j = 0; (matcher = setMatchers[j]); j++ ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	superMatcher.el = 0;
	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ expando ][ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !group ) {
			group = tokenize( selector );
		}
		i = group.length;
		while ( i-- ) {
			cached = matcherFromTokens( group[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
	}
	return cached;
};

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[i], results );
	}
	return results;
}

function select( selector, context, results, seed, xml ) {
	var i, tokens, token, type, find,
		match = tokenize( selector ),
		j = match.length;

	if ( !seed ) {
		// Try to minimize operations if there is only one group
		if ( match.length === 1 ) {

			// Take a shortcut and set the context if the root selector is an ID
			tokens = match[0] = match[0].slice( 0 );
			if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
					context.nodeType === 9 && !xml &&
					Expr.relative[ tokens[1].type ] ) {

				context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
				if ( !context ) {
					return results;
				}

				selector = selector.slice( tokens.shift().length );
			}

			// Fetch a seed set for right-to-left matching
			for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
				token = tokens[i];

				// Abort if we hit a combinator
				if ( Expr.relative[ (type = token.type) ] ) {
					break;
				}
				if ( (find = Expr.find[ type ]) ) {
					// Search, expanding context for leading sibling combinators
					if ( (seed = find(
						token.matches[0].replace( rbackslash, "" ),
						rsibling.test( tokens[0].type ) && context.parentNode || context,
						xml
					)) ) {

						// If seed is empty or no tokens remain, we can return early
						tokens.splice( i, 1 );
						selector = seed.length && tokens.join("");
						if ( !selector ) {
							push.apply( results, slice.call( seed, 0 ) );
							return results;
						}

						break;
					}
				}
			}
		}
	}

	// Compile and execute a filtering function
	// Provide `match` to avoid retokenization if we modified the selector above
	compile( selector, match )(
		seed,
		context,
		xml,
		results,
		rsibling.test( selector )
	);
	return results;
}

if ( document.querySelectorAll ) {
	(function() {
		var disconnectedMatch,
			oldSelect = select,
			rescape = /'|\\/g,
			rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,

			// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
			// A support test would require too much code (would include document ready)
			rbuggyQSA = [ ":focus" ],

			// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
			// A support test would require too much code (would include document ready)
			// just skip matchesSelector for :active
			rbuggyMatches = [ ":active" ],
			matches = docElem.matchesSelector ||
				docElem.mozMatchesSelector ||
				docElem.webkitMatchesSelector ||
				docElem.oMatchesSelector ||
				docElem.msMatchesSelector;

		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert(function( div ) {
			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explictly
			// setting a boolean content attribute,
			// since its presence should be enough
			// http://bugs.jquery.com/ticket/12359
			div.innerHTML = "<select><option selected=''></option></select>";

			// IE8 - Some boolean attributes are not treated correctly
			if ( !div.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here (do not put tests after this one)
			if ( !div.querySelectorAll(":checked").length ) {
				rbuggyQSA.push(":checked");
			}
		});

		assert(function( div ) {

			// Opera 10-12/IE9 - ^= $= *= and empty values
			// Should not select anything
			div.innerHTML = "<p test=''></p>";
			if ( div.querySelectorAll("[test^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here (do not put tests after this one)
			div.innerHTML = "<input type='hidden'/>";
			if ( !div.querySelectorAll(":enabled").length ) {
				rbuggyQSA.push(":enabled", ":disabled");
			}
		});

		// rbuggyQSA always contains :focus, so no need for a length check
		rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );

		select = function( selector, context, results, seed, xml ) {
			// Only use querySelectorAll when not filtering,
			// when this is not xml,
			// and when no QSA bugs apply
			if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
				var groups, i,
					old = true,
					nid = expando,
					newContext = context,
					newSelector = context.nodeType === 9 && selector;

				// qSA works strangely on Element-rooted queries
				// We can work around this by specifying an extra ID on the root
				// and working up from there (Thanks to Andrew Dupont for the technique)
				// IE 8 doesn't work on object elements
				if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
					groups = tokenize( selector );

					if ( (old = context.getAttribute("id")) ) {
						nid = old.replace( rescape, "\\$&" );
					} else {
						context.setAttribute( "id", nid );
					}
					nid = "[id='" + nid + "'] ";

					i = groups.length;
					while ( i-- ) {
						groups[i] = nid + groups[i].join("");
					}
					newContext = rsibling.test( selector ) && context.parentNode || context;
					newSelector = groups.join(",");
				}

				if ( newSelector ) {
					try {
						push.apply( results, slice.call( newContext.querySelectorAll(
							newSelector
						), 0 ) );
						return results;
					} catch(qsaError) {
					} finally {
						if ( !old ) {
							context.removeAttribute("id");
						}
					}
				}
			}

			return oldSelect( selector, context, results, seed, xml );
		};

		if ( matches ) {
			assert(function( div ) {
				// Check to see if it's possible to do matchesSelector
				// on a disconnected node (IE 9)
				disconnectedMatch = matches.call( div, "div" );

				// This should fail with an exception
				// Gecko does not error, returns false instead
				try {
					matches.call( div, "[test!='']:sizzle" );
					rbuggyMatches.push( "!=", pseudos );
				} catch ( e ) {}
			});

			// rbuggyMatches always contains :active and :focus, so no need for a length check
			rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );

			Sizzle.matchesSelector = function( elem, expr ) {
				// Make sure that attribute selectors are quoted
				expr = expr.replace( rattributeQuotes, "='$1']" );

				// rbuggyMatches always contains :active, so no need for an existence check
				if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
					try {
						var ret = matches.call( elem, expr );

						// IE 9's matchesSelector returns false on disconnected nodes
						if ( ret || disconnectedMatch ||
								// As well, disconnected nodes are said to be in a document
								// fragment in IE 9
								elem.document && elem.document.nodeType !== 11 ) {
							return ret;
						}
					} catch(e) {}
				}

				return Sizzle( expr, null, null, [ elem ] ).length > 0;
			};
		}
	})();
}

// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];

// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();

// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;


})( window );
var runtil = /Until$/,
	rparentsprev = /^(?:parents|prev(?:Until|All))/,
	isSimple = /^.[^:#\[\.,]*$/,
	rneedsContext = jQuery.expr.match.needsContext,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var i, l, length, n, r, ret,
			self = this;

		if ( typeof selector !== "string" ) {
			return jQuery( selector ).filter(function() {
				for ( i = 0, l = self.length; i < l; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			});
		}

		ret = this.pushStack( "", "find", selector );

		for ( i = 0, l = this.length; i < l; i++ ) {
			length = ret.length;
			jQuery.find( selector, this[i], ret );

			if ( i > 0 ) {
				// Make sure that the results are unique
				for ( n = length; n < ret.length; n++ ) {
					for ( r = 0; r < length; r++ ) {
						if ( ret[r] === ret[n] ) {
							ret.splice(n--, 1);
							break;
						}
					}
				}
			}
		}

		return ret;
	},

	has: function( target ) {
		var i,
			targets = jQuery( target, this ),
			len = targets.length;

		return this.filter(function() {
			for ( i = 0; i < len; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false), "not", selector);
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true), "filter", selector );
	},

	is: function( selector ) {
		return !!selector && (
			typeof selector === "string" ?
				// If this is a positional/relative selector, check membership in the returned set
				// so $("p:first").is("p:last") won't return true for a doc with two "p".
				rneedsContext.test( selector ) ?
					jQuery( selector, this.context ).index( this[0] ) >= 0 :
					jQuery.filter( selector, this ).length > 0 :
				this.filter( selector ).length > 0 );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			ret = [],
			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			cur = this[i];

			while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
					ret.push( cur );
					break;
				}
				cur = cur.parentNode;
			}
		}

		ret = ret.length > 1 ? jQuery.unique( ret ) : ret;

		return this.pushStack( ret, "closest", selectors );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
		}

		// index in selector
		if ( typeof elem === "string" ) {
			return jQuery.inArray( this[0], jQuery( elem ) );
		}

		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
			all :
			jQuery.unique( all ) );
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter(selector)
		);
	}
});

jQuery.fn.andSelf = jQuery.fn.addBack;

// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
	return !node || !node.parentNode || node.parentNode.nodeType === 11;
}

function sibling( cur, dir ) {
	do {
		cur = cur[ dir ];
	} while ( cur && cur.nodeType !== 1 );

	return cur;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until );

		if ( !runtil.test( name ) ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;

		if ( this.length > 1 && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}

		return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
			jQuery.find.matches(expr, elems);
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}

		return r;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {

	// Can't pass null or undefined to indexOf in Firefox 4
	// Set to 0 to skip string check
	qualifier = qualifier || 0;

	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			var retVal = !!qualifier.call( elem, i, elem );
			return retVal === keep;
		});

	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem, i ) {
			return ( elem === qualifier ) === keep;
		});

	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});

		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}

	return jQuery.grep(elements, function( elem, i ) {
		return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
	});
}
function createSafeFragment( document ) {
	var list = nodeNames.split( "|" ),
	safeFrag = document.createDocumentFragment();

	if ( safeFrag.createElement ) {
		while ( list.length ) {
			safeFrag.createElement(
				list.pop()
			);
		}
	}
	return safeFrag;
}

var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
		"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
	rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnoInnerhtml = /<(?:script|style|link)/i,
	rnocache = /<(?:script|object|embed|option|style)/i,
	rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
	rcheckableType = /^(?:checkbox|radio)$/,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /\/(java|ecma)script/i,
	rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		area: [ 1, "<map>", "</map>" ],
		_default: [ 0, "", "" ]
	},
	safeFragment = createSafeFragment( document ),
	fragmentDiv = safeFragment.appendChild( document.createElement("div") );

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
	wrapMap._default = [ 1, "X<div>", "</div>" ];
}

jQuery.fn.extend({
	text: function( value ) {
		return jQuery.access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
		}, null, value, arguments.length );
	},

	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}

		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);

			if ( this[0].parentNode ) {
				wrap.insertBefore( this[0] );
			}

			wrap.map(function() {
				var elem = this;

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				return elem;
			}).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}

		return this.each(function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		});
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each(function(i) {
			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
		});
	},

	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},

	append: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 ) {
				this.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 ) {
				this.insertBefore( elem, this.firstChild );
			}
		});
	},

	before: function() {
		if ( !isDisconnected( this[0] ) ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this );
			});
		}

		if ( arguments.length ) {
			var set = jQuery.clean( arguments );
			return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
		}
	},

	after: function() {
		if ( !isDisconnected( this[0] ) ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			});
		}

		if ( arguments.length ) {
			var set = jQuery.clean( arguments );
			return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
		}
	},

	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		var elem,
			i = 0;

		for ( ; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( elem.getElementsByTagName("*") );
					jQuery.cleanData( [ elem ] );
				}

				if ( elem.parentNode ) {
					elem.parentNode.removeChild( elem );
				}
			}
		}

		return this;
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( elem.getElementsByTagName("*") );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function () {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},

	html: function( value ) {
		return jQuery.access( this, function( value ) {
			var elem = this[0] || {},
				i = 0,
				l = this.length;

			if ( value === undefined ) {
				return elem.nodeType === 1 ?
					elem.innerHTML.replace( rinlinejQuery, "" ) :
					undefined;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				( jQuery.support.htmlSerialize || !rnoshimcache.test( value )  ) &&
				( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
				!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {

				value = value.replace( rxhtmlTag, "<$1></$2>" );

				try {
					for (; i < l; i++ ) {
						// Remove element nodes and prevent memory leaks
						elem = this[i] || {};
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( elem.getElementsByTagName( "*" ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch(e) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function( value ) {
		if ( !isDisconnected( this[0] ) ) {
			// Make sure that the elements are removed from the DOM before they are inserted
			// this can help fix replacing a parent with child elements
			if ( jQuery.isFunction( value ) ) {
				return this.each(function(i) {
					var self = jQuery(this), old = self.html();
					self.replaceWith( value.call( this, i, old ) );
				});
			}

			if ( typeof value !== "string" ) {
				value = jQuery( value ).detach();
			}

			return this.each(function() {
				var next = this.nextSibling,
					parent = this.parentNode;

				jQuery( this ).remove();

				if ( next ) {
					jQuery(next).before( value );
				} else {
					jQuery(parent).append( value );
				}
			});
		}

		return this.length ?
			this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
			this;
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, table, callback ) {

		// Flatten any nested arrays
		args = [].concat.apply( [], args );

		var results, first, fragment, iNoClone,
			i = 0,
			value = args[0],
			scripts = [],
			l = this.length;

		// We can't cloneNode fragments that contain checked, in WebKit
		if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
			return this.each(function() {
				jQuery(this).domManip( args, table, callback );
			});
		}

		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				args[0] = value.call( this, i, table ? self.html() : undefined );
				self.domManip( args, table, callback );
			});
		}

		if ( this[0] ) {
			results = jQuery.buildFragment( args, this, scripts );
			fragment = results.fragment;
			first = fragment.firstChild;

			if ( fragment.childNodes.length === 1 ) {
				fragment = first;
			}

			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );

				// Use the original fragment for the last item instead of the first because it can end up
				// being emptied incorrectly in certain situations (#8070).
				// Fragments from the fragment cache must always be cloned and never used in place.
				for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
					callback.call(
						table && jQuery.nodeName( this[i], "table" ) ?
							findOrAppend( this[i], "tbody" ) :
							this[i],
						i === iNoClone ?
							fragment :
							jQuery.clone( fragment, true, true )
					);
				}
			}

			// Fix #11809: Avoid leaking memory
			fragment = first = null;

			if ( scripts.length ) {
				jQuery.each( scripts, function( i, elem ) {
					if ( elem.src ) {
						if ( jQuery.ajax ) {
							jQuery.ajax({
								url: elem.src,
								type: "GET",
								dataType: "script",
								async: false,
								global: false,
								"throws": true
							});
						} else {
							jQuery.error("no ajax");
						}
					} else {
						jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
					}

					if ( elem.parentNode ) {
						elem.parentNode.removeChild( elem );
					}
				});
			}
		}

		return this;
	}
});

function findOrAppend( elem, tag ) {
	return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}

function cloneCopyEvent( src, dest ) {

	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var type, i, l,
		oldData = jQuery._data( src ),
		curData = jQuery._data( dest, oldData ),
		events = oldData.events;

	if ( events ) {
		delete curData.handle;
		curData.events = {};

		for ( type in events ) {
			for ( i = 0, l = events[ type ].length; i < l; i++ ) {
				jQuery.event.add( dest, type, events[ type ][ i ] );
			}
		}
	}

	// make the cloned public data object a copy from the original
	if ( curData.data ) {
		curData.data = jQuery.extend( {}, curData.data );
	}
}

function cloneFixAttributes( src, dest ) {
	var nodeName;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	// clearAttributes removes the attributes, which we don't want,
	// but also removes the attachEvent events, which we *do* want
	if ( dest.clearAttributes ) {
		dest.clearAttributes();
	}

	// mergeAttributes, in contrast, only merges back on the
	// original attributes, not the events
	if ( dest.mergeAttributes ) {
		dest.mergeAttributes( src );
	}

	nodeName = dest.nodeName.toLowerCase();

	if ( nodeName === "object" ) {
		// IE6-10 improperly clones children of object elements using classid.
		// IE10 throws NoModificationAllowedError if parent is null, #12132.
		if ( dest.parentNode ) {
			dest.outerHTML = src.outerHTML;
		}

		// This path appears unavoidable for IE9. When cloning an object
		// element in IE9, the outerHTML strategy above is not sufficient.
		// If the src has innerHTML and the destination does not,
		// copy the src.innerHTML into the dest.innerHTML. #10324
		if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
			dest.innerHTML = src.innerHTML;
		}

	} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set

		dest.defaultChecked = dest.checked = src.checked;

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;

	// IE blanks contents when cloning scripts
	} else if ( nodeName === "script" && dest.text !== src.text ) {
		dest.text = src.text;
	}

	// Event data gets referenced instead of copied if the expando
	// gets copied too
	dest.removeAttribute( jQuery.expando );
}

jQuery.buildFragment = function( args, context, scripts ) {
	var fragment, cacheable, cachehit,
		first = args[ 0 ];

	// Set context from what may come in as undefined or a jQuery collection or a node
	// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
	// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
	context = context || document;
	context = !context.nodeType && context[0] || context;
	context = context.ownerDocument || context;

	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
	// Cloning options loses the selected state, so don't cache them
	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
	// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
	if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
		first.charAt(0) === "<" && !rnocache.test( first ) &&
		(jQuery.support.checkClone || !rchecked.test( first )) &&
		(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {

		// Mark cacheable and look for a hit
		cacheable = true;
		fragment = jQuery.fragments[ first ];
		cachehit = fragment !== undefined;
	}

	if ( !fragment ) {
		fragment = context.createDocumentFragment();
		jQuery.clean( args, context, fragment, scripts );

		// Update the cache, but only store false
		// unless this is a second parsing of the same content
		if ( cacheable ) {
			jQuery.fragments[ first ] = cachehit && fragment;
		}
	}

	return { fragment: fragment, cacheable: cacheable };
};

jQuery.fragments = {};

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			i = 0,
			ret = [],
			insert = jQuery( selector ),
			l = insert.length,
			parent = this.length === 1 && this[0].parentNode;

		if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
			insert[ original ]( this[0] );
			return this;
		} else {
			for ( ; i < l; i++ ) {
				elems = ( i > 0 ? this.clone(true) : this ).get();
				jQuery( insert[i] )[ original ]( elems );
				ret = ret.concat( elems );
			}

			return this.pushStack( ret, name, insert.selector );
		}
	};
});

function getAll( elem ) {
	if ( typeof elem.getElementsByTagName !== "undefined" ) {
		return elem.getElementsByTagName( "*" );

	} else if ( typeof elem.querySelectorAll !== "undefined" ) {
		return elem.querySelectorAll( "*" );

	} else {
		return [];
	}
}

// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( rcheckableType.test( elem.type ) ) {
		elem.defaultChecked = elem.checked;
	}
}

jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var srcElements,
			destElements,
			i,
			clone;

		if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
			clone = elem.cloneNode( true );

		// IE<=8 does not properly clone detached, unknown element nodes
		} else {
			fragmentDiv.innerHTML = elem.outerHTML;
			fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
		}

		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
			// IE copies events bound via attachEvent when using cloneNode.
			// Calling detachEvent on the clone will also remove the events
			// from the original. In order to get around this, we use some
			// proprietary methods to clear the events. Thanks to MooTools
			// guys for this hotness.

			cloneFixAttributes( elem, clone );

			// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
			srcElements = getAll( elem );
			destElements = getAll( clone );

			// Weird iteration because IE will replace the length property
			// with an element if you are cloning the body and one of the
			// elements on the page has a name or id of "length"
			for ( i = 0; srcElements[i]; ++i ) {
				// Ensure that the destination node is not null; Fixes #9587
				if ( destElements[i] ) {
					cloneFixAttributes( srcElements[i], destElements[i] );
				}
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			cloneCopyEvent( elem, clone );

			if ( deepDataAndEvents ) {
				srcElements = getAll( elem );
				destElements = getAll( clone );

				for ( i = 0; srcElements[i]; ++i ) {
					cloneCopyEvent( srcElements[i], destElements[i] );
				}
			}
		}

		srcElements = destElements = null;

		// Return the cloned set
		return clone;
	},

	clean: function( elems, context, fragment, scripts ) {
		var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
			safe = context === document && safeFragment,
			ret = [];

		// Ensure that context is a document
		if ( !context || typeof context.createDocumentFragment === "undefined" ) {
			context = document;
		}

		// Use the already-created safe fragment if context permits
		for ( i = 0; (elem = elems[i]) != null; i++ ) {
			if ( typeof elem === "number" ) {
				elem += "";
			}

			if ( !elem ) {
				continue;
			}

			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				if ( !rhtml.test( elem ) ) {
					elem = context.createTextNode( elem );
				} else {
					// Ensure a safe container in which to render the html
					safe = safe || createSafeFragment( context );
					div = context.createElement("div");
					safe.appendChild( div );

					// Fix "XHTML"-style tags in all browsers
					elem = elem.replace(rxhtmlTag, "<$1></$2>");

					// Go to html and back, then peel off extra wrappers
					tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
					wrap = wrapMap[ tag ] || wrapMap._default;
					depth = wrap[0];
					div.innerHTML = wrap[1] + elem + wrap[2];

					// Move to the right depth
					while ( depth-- ) {
						div = div.lastChild;
					}

					// Remove IE's autoinserted <tbody> from table fragments
					if ( !jQuery.support.tbody ) {

						// String was a <table>, *may* have spurious <tbody>
						hasBody = rtbody.test(elem);
							tbody = tag === "table" && !hasBody ?
								div.firstChild && div.firstChild.childNodes :

								// String was a bare <thead> or <tfoot>
								wrap[1] === "<table>" && !hasBody ?
									div.childNodes :
									[];

						for ( j = tbody.length - 1; j >= 0 ; --j ) {
							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
								tbody[ j ].parentNode.removeChild( tbody[ j ] );
							}
						}
					}

					// IE completely kills leading whitespace when innerHTML is used
					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
						div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
					}

					elem = div.childNodes;

					// Take out of fragment container (we need a fresh div each time)
					div.parentNode.removeChild( div );
				}
			}

			if ( elem.nodeType ) {
				ret.push( elem );
			} else {
				jQuery.merge( ret, elem );
			}
		}

		// Fix #11356: Clear elements from safeFragment
		if ( div ) {
			elem = div = safe = null;
		}

		// Reset defaultChecked for any radios and checkboxes
		// about to be appended to the DOM in IE 6/7 (#8060)
		if ( !jQuery.support.appendChecked ) {
			for ( i = 0; (elem = ret[i]) != null; i++ ) {
				if ( jQuery.nodeName( elem, "input" ) ) {
					fixDefaultChecked( elem );
				} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
					jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
				}
			}
		}

		// Append elements to a provided document fragment
		if ( fragment ) {
			// Special handling of each script element
			handleScript = function( elem ) {
				// Check if we consider it executable
				if ( !elem.type || rscriptType.test( elem.type ) ) {
					// Detach the script and store it in the scripts array (if provided) or the fragment
					// Return truthy to indicate that it has been handled
					return scripts ?
						scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
						fragment.appendChild( elem );
				}
			};

			for ( i = 0; (elem = ret[i]) != null; i++ ) {
				// Check if we're done after handling an executable script
				if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
					// Append to fragment and handle embedded scripts
					fragment.appendChild( elem );
					if ( typeof elem.getElementsByTagName !== "undefined" ) {
						// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
						jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );

						// Splice the scripts into ret after their former ancestor and advance our index beyond them
						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
						i += jsTags.length;
					}
				}
			}
		}

		return ret;
	},

	cleanData: function( elems, /* internal */ acceptData ) {
		var data, id, elem, type,
			i = 0,
			internalKey = jQuery.expando,
			cache = jQuery.cache,
			deleteExpando = jQuery.support.deleteExpando,
			special = jQuery.event.special;

		for ( ; (elem = elems[i]) != null; i++ ) {

			if ( acceptData || jQuery.acceptData( elem ) ) {

				id = elem[ internalKey ];
				data = id && cache[ id ];

				if ( data ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Remove cache only if it was not already removed by jQuery.event.remove
					if ( cache[ id ] ) {

						delete cache[ id ];

						// IE does not allow us to delete expando properties from nodes,
						// nor does it have a removeAttribute function on Document nodes;
						// we must handle all of these cases
						if ( deleteExpando ) {
							delete elem[ internalKey ];

						} else if ( elem.removeAttribute ) {
							elem.removeAttribute( internalKey );

						} else {
							elem[ internalKey ] = null;
						}

						jQuery.deletedIds.push( id );
					}
				}
			}
		}
	}
});
// Limit scope pollution from any deprecated API
(function() {

var matched, browser;

// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
	ua = ua.toLowerCase();

	var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
		/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
		/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
		/(msie) ([\w.]+)/.exec( ua ) ||
		ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
		[];

	return {
		browser: match[ 1 ] || "",
		version: match[ 2 ] || "0"
	};
};

matched = jQuery.uaMatch( navigator.userAgent );
browser = {};

if ( matched.browser ) {
	browser[ matched.browser ] = true;
	browser.version = matched.version;
}

// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
	browser.webkit = true;
} else if ( browser.webkit ) {
	browser.safari = true;
}

jQuery.browser = browser;

jQuery.sub = function() {
	function jQuerySub( selector, context ) {
		return new jQuerySub.fn.init( selector, context );
	}
	jQuery.extend( true, jQuerySub, this );
	jQuerySub.superclass = this;
	jQuerySub.fn = jQuerySub.prototype = this();
	jQuerySub.fn.constructor = jQuerySub;
	jQuerySub.sub = this.sub;
	jQuerySub.fn.init = function init( selector, context ) {
		if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
			context = jQuerySub( context );
		}

		return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
	};
	jQuerySub.fn.init.prototype = jQuerySub.fn;
	var rootjQuerySub = jQuerySub(document);
	return jQuerySub;
};

})();
var curCSS, iframe, iframeDoc,
	ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rposition = /^(top|right|bottom|left)$/,
	// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
	// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rmargin = /^margin/,
	rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
	rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
	rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
	elemdisplay = { BODY: "block" },

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: 0,
		fontWeight: 400
	},

	cssExpand = [ "Top", "Right", "Bottom", "Left" ],
	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],

	eventsToggle = jQuery.fn.toggle;

// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {

	// shortcut for names that are not vendor prefixed
	if ( name in style ) {
		return name;
	}

	// check for vendor prefixed names
	var capName = name.charAt(0).toUpperCase() + name.slice(1),
		origName = name,
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in style ) {
			return name;
		}
	}

	return origName;
}

function isHidden( elem, el ) {
	elem = el || elem;
	return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}

function showHide( elements, show ) {
	var elem, display,
		values = [],
		index = 0,
		length = elements.length;

	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}
		values[ index ] = jQuery._data( elem, "olddisplay" );
		if ( show ) {
			// Reset the inline display of this element to learn if it is
			// being hidden by cascaded rules or not
			if ( !values[ index ] && elem.style.display === "none" ) {
				elem.style.display = "";
			}

			// Set elements which have been overridden with display: none
			// in a stylesheet to whatever the default browser style is
			// for such an element
			if ( elem.style.display === "" && isHidden( elem ) ) {
				values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
			}
		} else {
			display = curCSS( elem, "display" );

			if ( !values[ index ] && display !== "none" ) {
				jQuery._data( elem, "olddisplay", display );
			}
		}
	}

	// Set the display of most of the elements in a second loop
	// to avoid the constant reflow
	for ( index = 0; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}
		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
			elem.style.display = show ? values[ index ] || "" : "none";
		}
	}

	return elements;
}

jQuery.fn.extend({
	css: function( name, value ) {
		return jQuery.access( this, function( elem, name, value ) {
			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	},
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state, fn2 ) {
		var bool = typeof state === "boolean";

		if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
			return eventsToggle.apply( this, arguments );
		}

		return this.each(function() {
			if ( bool ? state : isHidden( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		});
	}
});

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;

				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"fillOpacity": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = jQuery.camelCase( name ),
			style = elem.style;

		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// convert relative number strings (+= or -=) to relative numbers. #7345
			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
				// Fixes bug #9237
				type = "number";
			}

			// Make sure that NaN and null values aren't set. See: #7116
			if ( value == null || type === "number" && isNaN( value ) ) {
				return;
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, numeric, extra ) {
		var val, num, hooks,
			origName = jQuery.camelCase( name );

		// Make sure that we're working with the right name
		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );

		// gets hook for the prefixed version
		// followed by the unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name );
		}

		//convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Return, converting to number if forced or a qualifier was provided and val looks numeric
		if ( numeric || extra !== undefined ) {
			num = parseFloat( val );
			return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
		}
		return val;
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var ret, name,
			old = {};

		// Remember the old values, and insert the new ones
		for ( name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		ret = callback.call( elem );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}

		return ret;
	}
});

// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
	curCSS = function( elem, name ) {
		var ret, width, minWidth, maxWidth,
			computed = window.getComputedStyle( elem, null ),
			style = elem.style;

		if ( computed ) {

			// getPropertyValue is only needed for .css('filter') in IE9, see #12537
			ret = computed.getPropertyValue( name ) || computed[ name ];

			if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
				ret = jQuery.style( elem, name );
			}

			// A tribute to the "awesome hack by Dean Edwards"
			// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
			// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
			// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
			if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
				width = style.width;
				minWidth = style.minWidth;
				maxWidth = style.maxWidth;

				style.minWidth = style.maxWidth = style.width = ret;
				ret = computed.width;

				style.width = width;
				style.minWidth = minWidth;
				style.maxWidth = maxWidth;
			}
		}

		return ret;
	};
} else if ( document.documentElement.currentStyle ) {
	curCSS = function( elem, name ) {
		var left, rsLeft,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			style = elem.style;

		// Avoid setting ret to empty string here
		// so we don't default to auto
		if ( ret == null && style && style[ name ] ) {
			ret = style[ name ];
		}

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		// but not position css attributes, as those are proportional to the parent element instead
		// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
		if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

			// Remember the original values
			left = style.left;
			rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				elem.runtimeStyle.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : ret;
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret === "" ? "auto" : ret;
	};
}

function setPositiveNumber( elem, value, subtract ) {
	var matches = rnumsplit.exec( value );
	return matches ?
			Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
			value;
}

function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
	var i = extra === ( isBorderBox ? "border" : "content" ) ?
		// If we already have the right measurement, avoid augmentation
		4 :
		// Otherwise initialize for horizontal or vertical properties
		name === "width" ? 1 : 0,

		val = 0;

	for ( ; i < 4; i += 2 ) {
		// both box models exclude margin, so add it if we want it
		if ( extra === "margin" ) {
			// we use jQuery.css instead of curCSS here
			// because of the reliableMarginRight CSS hook!
			val += jQuery.css( elem, extra + cssExpand[ i ], true );
		}

		// From this point on we use curCSS for maximum performance (relevant in animations)
		if ( isBorderBox ) {
			// border-box includes padding, so remove it if we want content
			if ( extra === "content" ) {
				val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
			}

			// at this point, extra isn't border nor margin, so remove border
			if ( extra !== "margin" ) {
				val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
			}
		} else {
			// at this point, extra isn't content, so add padding
			val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;

			// at this point, extra isn't content nor padding, so add border
			if ( extra !== "padding" ) {
				val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
			}
		}
	}

	return val;
}

function getWidthOrHeight( elem, name, extra ) {

	// Start with offset property, which is equivalent to the border-box value
	var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
		valueIsBorderBox = true,
		isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";

	// some non-html elements return undefined for offsetWidth, so check for null/undefined
	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
	if ( val <= 0 || val == null ) {
		// Fall back to computed then uncomputed css if necessary
		val = curCSS( elem, name );
		if ( val < 0 || val == null ) {
			val = elem.style[ name ];
		}

		// Computed unit is not pixels. Stop here and return.
		if ( rnumnonpx.test(val) ) {
			return val;
		}

		// we need the check for style in case a browser which returns unreliable values
		// for getComputedStyle silently falls back to the reliable elem.style
		valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );

		// Normalize "", auto, and prepare for extra
		val = parseFloat( val ) || 0;
	}

	// use the active box-sizing model to add/subtract irrelevant styles
	return ( val +
		augmentWidthOrHeight(
			elem,
			name,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox
		)
	) + "px";
}


// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
	if ( elemdisplay[ nodeName ] ) {
		return elemdisplay[ nodeName ];
	}

	var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
		display = elem.css("display");
	elem.remove();

	// If the simple way fails,
	// get element's real default display by attaching it to a temp iframe
	if ( display === "none" || display === "" ) {
		// Use the already-created iframe if possible
		iframe = document.body.appendChild(
			iframe || jQuery.extend( document.createElement("iframe"), {
				frameBorder: 0,
				width: 0,
				height: 0
			})
		);

		// Create a cacheable copy of the iframe document on first call.
		// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
		// document to it; WebKit & Firefox won't allow reusing the iframe document.
		if ( !iframeDoc || !iframe.createElement ) {
			iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
			iframeDoc.write("<!doctype html><html><body>");
			iframeDoc.close();
		}

		elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );

		display = curCSS( elem, "display" );
		document.body.removeChild( iframe );
	}

	// Store the correct default display
	elemdisplay[ nodeName ] = display;

	return display;
}

jQuery.each([ "height", "width" ], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {
				// certain elements can have dimension info if we invisibly show them
				// however, it must have a current display style that would benefit from this
				if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
					return jQuery.swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, name, extra );
					});
				} else {
					return getWidthOrHeight( elem, name, extra );
				}
			}
		},

		set: function( elem, value, extra ) {
			return setPositiveNumber( elem, value, extra ?
				augmentWidthOrHeight(
					elem,
					name,
					extra,
					jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
				) : 0
			);
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
				( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle,
				opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
			if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
				style.removeAttribute ) {

				// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
				// if "filter:" is present at all, clearType is disabled, we want to avoid this
				// style.removeAttribute is IE Only, but so apparently is this code path...
				style.removeAttribute( "filter" );

				// if there there is no filter style applied in a css rule, we are done
				if ( currentStyle && !currentStyle.filter ) {
					return;
				}
			}

			// otherwise, set new filter values
			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
	if ( !jQuery.support.reliableMarginRight ) {
		jQuery.cssHooks.marginRight = {
			get: function( elem, computed ) {
				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
				// Work around by temporarily setting element display to inline-block
				return jQuery.swap( elem, { "display": "inline-block" }, function() {
					if ( computed ) {
						return curCSS( elem, "marginRight" );
					}
				});
			}
		};
	}

	// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
	// getComputedStyle returns percent when specified for top/left/bottom/right
	// rather than make the css module depend on the offset module, we just check for it here
	if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
		jQuery.each( [ "top", "left" ], function( i, prop ) {
			jQuery.cssHooks[ prop ] = {
				get: function( elem, computed ) {
					if ( computed ) {
						var ret = curCSS( elem, prop );
						// if curCSS returns percentage, fallback to offset
						return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
					}
				}
			};
		});
	}

});

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}

// These hooks are used by animate to expand properties
jQuery.each({
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i,

				// assumes a single number if not a string
				parts = typeof value === "string" ? value.split(" ") : [ value ],
				expanded = {};

			for ( i = 0; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( !rmargin.test( prefix ) ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
});
var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	rselectTextarea = /^(?:select|textarea)/i;

jQuery.fn.extend({
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray( this.elements ) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				( this.checked || rselectTextarea.test( this.nodeName ) ||
					rinput.test( this.type ) );
		})
		.map(function( i, elem ){
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val, i ){
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					}) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		}).get();
	}
});

//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, value ) {
			// If value is a function, invoke it and return its value
			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
		};

	// Set traditional to true for jQuery <= 1.3.2 behavior.
	if ( traditional === undefined ) {
		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		});

	} else {
		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" ).replace( r20, "+" );
};

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( jQuery.isArray( obj ) ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );

			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && jQuery.type( obj ) === "object" ) {
		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}
var
	// Document location
	ajaxLocParts,
	ajaxLocation,

	rhash = /#.*$/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rquery = /\?/,
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rts = /([?&])_=[^&]*/,
	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,

	// Keep a copy of the old load method
	_load = jQuery.fn.load,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = ["*/"] + ["*"];

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.href;
}

// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType, list, placeBefore,
			dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
			i = 0,
			length = dataTypes.length;

		if ( jQuery.isFunction( func ) ) {
			// For each dataType in the dataTypeExpression
			for ( ; i < length; i++ ) {
				dataType = dataTypes[ i ];
				// We control if we're asked to add before
				// any existing element
				placeBefore = /^\+/.test( dataType );
				if ( placeBefore ) {
					dataType = dataType.substr( 1 ) || "*";
				}
				list = structure[ dataType ] = structure[ dataType ] || [];
				// then we add to the structure accordingly
				list[ placeBefore ? "unshift" : "push" ]( func );
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
		dataType /* internal */, inspected /* internal */ ) {

	dataType = dataType || options.dataTypes[ 0 ];
	inspected = inspected || {};

	inspected[ dataType ] = true;

	var selection,
		list = structure[ dataType ],
		i = 0,
		length = list ? list.length : 0,
		executeOnly = ( structure === prefilters );

	for ( ; i < length && ( executeOnly || !selection ); i++ ) {
		selection = list[ i ]( options, originalOptions, jqXHR );
		// If we got redirected to another dataType
		// we try there if executing only and not done already
		if ( typeof selection === "string" ) {
			if ( !executeOnly || inspected[ selection ] ) {
				selection = undefined;
			} else {
				options.dataTypes.unshift( selection );
				selection = inspectPrefiltersOrTransports(
						structure, options, originalOptions, jqXHR, selection, inspected );
			}
		}
	}
	// If we're only executing or nothing was selected
	// we try the catchall dataType if not done already
	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
		selection = inspectPrefiltersOrTransports(
				structure, options, originalOptions, jqXHR, "*", inspected );
	}
	// unnecessary when only executing (prefilters)
	// but it'll be ignored by the caller in that case
	return selection;
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};
	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}
}

jQuery.fn.load = function( url, params, callback ) {
	if ( typeof url !== "string" && _load ) {
		return _load.apply( this, arguments );
	}

	// Don't do a request if no elements are being requested
	if ( !this.length ) {
		return this;
	}

	var selector, type, response,
		self = this,
		off = url.indexOf(" ");

	if ( off >= 0 ) {
		selector = url.slice( off, url.length );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( jQuery.isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// Request the remote document
	jQuery.ajax({
		url: url,

		// if "type" variable is undefined, then "GET" method will be used
		type: type,
		dataType: "html",
		data: params,
		complete: function( jqXHR, status ) {
			if ( callback ) {
				self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
			}
		}
	}).done(function( responseText ) {

		// Save response for use in complete callback
		response = arguments;

		// See if a selector was specified
		self.html( selector ?

			// Create a dummy div to hold the results
			jQuery("<div>")

				// inject the contents of the document in, removing the scripts
				// to avoid any 'Permission Denied' errors in IE
				.append( responseText.replace( rscript, "" ) )

				// Locate the specified elements
				.find( selector ) :

			// If not, just inject the full result
			responseText );

	});

	return this;
};

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
	jQuery.fn[ o ] = function( f ){
		return this.on( o, f );
	};
});

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {
		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		return jQuery.ajax({
			type: method,
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	};
});

jQuery.extend({

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		if ( settings ) {
			// Building a settings object
			ajaxExtend( target, jQuery.ajaxSettings );
		} else {
			// Extending ajaxSettings
			settings = target;
			target = jQuery.ajaxSettings;
		}
		ajaxExtend( target, settings );
		return target;
	},

	ajaxSettings: {
		url: ajaxLocation,
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			text: "text/plain",
			json: "application/json, text/javascript",
			"*": allTypes
		},

		contents: {
			xml: /xml/,
			html: /html/,
			json: /json/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText"
		},

		// List of data converters
		// 1) key format is "source_type destination_type" (a single space in-between)
		// 2) the catchall symbol "*" can be used for source_type
		converters: {

			// Convert anything to text
			"* text": window.String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			context: true,
			url: true
		}
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var // ifModified key
			ifModifiedKey,
			// Response headers
			responseHeadersString,
			responseHeaders,
			// transport
			transport,
			// timeout handle
			timeoutTimer,
			// Cross-domain detection vars
			parts,
			// To know if global events are to be dispatched
			fireGlobals,
			// Loop variable
			i,
			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),
			// Callbacks context
			callbackContext = s.context || s,
			// Context for global events
			// It's the callbackContext if one was provided in the options
			// and if it's a DOM node or a jQuery collection
			globalEventContext = callbackContext !== s &&
				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
						jQuery( callbackContext ) : jQuery.event,
			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),
			// Status-dependent callbacks
			statusCode = s.statusCode || {},
			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},
			// The jqXHR state
			state = 0,
			// Default abort message
			strAbort = "canceled",
			// Fake xhr
			jqXHR = {

				readyState: 0,

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( !state ) {
						var lname = name.toLowerCase();
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match === undefined ? null : match;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					statusText = statusText || strAbort;
					if ( transport ) {
						transport.abort( statusText );
					}
					done( 0, statusText );
					return this;
				}
			};

		// Callback for when everything is done
		// It is defined here because jslint complains if it is declared
		// at the end of the function (which would be more logical and readable)
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// If successful, handle type chaining
			if ( status >= 200 && status < 300 || status === 304 ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {

					modified = jqXHR.getResponseHeader("Last-Modified");
					if ( modified ) {
						jQuery.lastModified[ ifModifiedKey ] = modified;
					}
					modified = jqXHR.getResponseHeader("Etag");
					if ( modified ) {
						jQuery.etag[ ifModifiedKey ] = modified;
					}
				}

				// If not modified
				if ( status === 304 ) {

					statusText = "notmodified";
					isSuccess = true;

				// If we have data
				} else {

					isSuccess = ajaxConvert( s, response );
					statusText = isSuccess.state;
					success = isSuccess.data;
					error = isSuccess.error;
					isSuccess = !error;
				}
			} else {
				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if ( !statusText || status ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
						[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		// Attach deferreds
		deferred.promise( jqXHR );
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;
		jqXHR.complete = completeDeferred.add;

		// Status-dependent callbacks
		jqXHR.statusCode = function( map ) {
			if ( map ) {
				var tmp;
				if ( state < 2 ) {
					for ( tmp in map ) {
						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
					}
				} else {
					tmp = map[ jqXHR.status ];
					jqXHR.always( tmp );
				}
			}
			return this;
		};

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// We also use the url parameter if available
		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );

		// A cross-domain request is in order when we have a protocol:host:port mismatch
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
			);
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( state === 2 ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		fireGlobals = s.global;

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Get ifModifiedKey before adding the anti-cache parameter
			ifModifiedKey = s.url;

			// Add anti-cache in url if needed
			if ( s.cache === false ) {

				var ts = jQuery.now(),
					// try replacing _= if it is there
					ret = s.url.replace( rts, "$1_=" + ts );

				// if nothing was replaced, add timestamp to the end
				s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			ifModifiedKey = ifModifiedKey || s.url;
			if ( jQuery.lastModified[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
			}
			if ( jQuery.etag[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
			}
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
				// Abort if not done already and return
				return jqXHR.abort();

		}

		// aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;
			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = setTimeout( function(){
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch (e) {
				// Propagate exception as error if not done
				if ( state < 2 ) {
					done( -1, e );
				// Simply rethrow otherwise
				} else {
					throw e;
				}
			}
		}

		return jqXHR;
	},

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {}

});

/* Handles responses to an ajax request:
 * - sets all responseXXX fields accordingly
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields;

	// Fill responseXXX fields
	for ( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}

	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {

	var conv, conv2, current, tmp,
		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice(),
		prev = dataTypes[ 0 ],
		converters = {},
		i = 0;

	// Apply the dataFilter if provided
	if ( s.dataFilter ) {
		response = s.dataFilter( response, s.dataType );
	}

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	// Convert to each sequential dataType, tolerating list modification
	for ( ; (current = dataTypes[++i]); ) {

		// There's only work to do if current dataType is non-auto
		if ( current !== "*" ) {

			// Convert response if prev dataType is non-auto and differs from current
			if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split(" ");
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {
								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.splice( i--, 0, current );
								}

								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s["throws"] ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
						}
					}
				}
			}

			// Update prev for next iteration
			prev = current;
		}
	}

	return { state: "success", data: response };
}
var oldCallbacks = [],
	rquestion = /\?/,
	rjsonp = /(=)\?(?=&|$)|\?\?/,
	nonce = jQuery.now();

// Default jsonp settings
jQuery.ajaxSetup({
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
});

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		data = s.data,
		url = s.url,
		hasCallback = s.jsonp !== false,
		replaceInUrl = hasCallback && rjsonp.test( url ),
		replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
			!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
			rjsonp.test( data );

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;
		overwritten = window[ callbackName ];

		// Insert callback into url or form data
		if ( replaceInUrl ) {
			s.url = url.replace( rjsonp, "$1" + callbackName );
		} else if ( replaceInData ) {
			s.data = data.replace( rjsonp, "$1" + callbackName );
		} else if ( hasCallback ) {
			s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters["script json"] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always(function() {
			// Restore preexisting value
			window[ callbackName ] = overwritten;

			// Save back as free
			if ( s[ callbackName ] ) {
				// make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		});

		// Delegate to script
		return "script";
	}
});
// Install script dataType
jQuery.ajaxSetup({
	accepts: {
		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /javascript|ecmascript/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
});

// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
});

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement( "script" );

				script.async = "async";

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}

						// Dereference the script
						script = undefined;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};
				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
				// This arises when a base node is used (#2709 and #4378).
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( 0, 1 );
				}
			}
		};
	}
});
var xhrCallbacks,
	// #5280: Internet Explorer will keep connections alive if we don't abort on unload
	xhrOnUnloadAbort = window.ActiveXObject ? function() {
		// Abort all pending requests
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( 0, 1 );
		}
	} : false,
	xhrId = 0;

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}

// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
	/* Microsoft failed to properly
	 * implement the XMLHttpRequest in IE7 (can't request local files),
	 * so we use the ActiveXObject when it is available
	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
	 * we need a fallback.
	 */
	function() {
		return !this.isLocal && createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

// Determine support properties
(function( xhr ) {
	jQuery.extend( jQuery.support, {
		ajax: !!xhr,
		cors: !!xhr && ( "withCredentials" in xhr )
	});
})( jQuery.ajaxSettings.xhr() );

// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {

	jQuery.ajaxTransport(function( s ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !s.crossDomain || jQuery.support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {

					// Get a new xhr
					var handle, i,
						xhr = s.xhr();

					// Open the socket
					// Passing null username, generates a login popup on Opera (#2865)
					if ( s.username ) {
						xhr.open( s.type, s.url, s.async, s.username, s.password );
					} else {
						xhr.open( s.type, s.url, s.async );
					}

					// Apply custom fields if provided
					if ( s.xhrFields ) {
						for ( i in s.xhrFields ) {
							xhr[ i ] = s.xhrFields[ i ];
						}
					}

					// Override mime type if needed
					if ( s.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( s.mimeType );
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
						headers[ "X-Requested-With" ] = "XMLHttpRequest";
					}

					// Need an extra try/catch for cross domain requests in Firefox 3
					try {
						for ( i in headers ) {
							xhr.setRequestHeader( i, headers[ i ] );
						}
					} catch( _ ) {}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( s.hasContent && s.data ) || null );

					// Listener
					callback = function( _, isAbort ) {

						var status,
							statusText,
							responseHeaders,
							responses,
							xml;

						// Firefox throws exceptions when accessing properties
						// of an xhr when a network error occurred
						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
						try {

							// Was never called and is aborted or complete
							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {

								// Only called once
								callback = undefined;

								// Do not keep as active anymore
								if ( handle ) {
									xhr.onreadystatechange = jQuery.noop;
									if ( xhrOnUnloadAbort ) {
										delete xhrCallbacks[ handle ];
									}
								}

								// If it's an abort
								if ( isAbort ) {
									// Abort it manually if needed
									if ( xhr.readyState !== 4 ) {
										xhr.abort();
									}
								} else {
									status = xhr.status;
									responseHeaders = xhr.getAllResponseHeaders();
									responses = {};
									xml = xhr.responseXML;

									// Construct response list
									if ( xml && xml.documentElement /* #4958 */ ) {
										responses.xml = xml;
									}

									// When requesting binary data, IE6-9 will throw an exception
									// on any attempt to access responseText (#11426)
									try {
										responses.text = xhr.responseText;
									} catch( e ) {
									}

									// Firefox throws an exception when accessing
									// statusText for faulty cross-domain requests
									try {
										statusText = xhr.statusText;
									} catch( e ) {
										// We normalize with Webkit giving an empty statusText
										statusText = "";
									}

									// Filter status for non standard behaviors

									// If the request is local and we have data: assume a success
									// (success with no data won't get notified, that's the best we
									// can do given current implementations)
									if ( !status && s.isLocal && !s.crossDomain ) {
										status = responses.text ? 200 : 404;
									// IE - #1450: sometimes returns 1223 when it should be 204
									} else if ( status === 1223 ) {
										status = 204;
									}
								}
							}
						} catch( firefoxAccessException ) {
							if ( !isAbort ) {
								complete( -1, firefoxAccessException );
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, responseHeaders );
						}
					};

					if ( !s.async ) {
						// if we're in sync mode we fire the callback
						callback();
					} else if ( xhr.readyState === 4 ) {
						// (IE6 & IE7) if it's in cache and has been
						// retrieved directly we need to fire the callback
						setTimeout( callback, 0 );
					} else {
						handle = ++xhrId;
						if ( xhrOnUnloadAbort ) {
							// Create the active xhrs callbacks list if needed
							// and attach the unload handler
							if ( !xhrCallbacks ) {
								xhrCallbacks = {};
								jQuery( window ).unload( xhrOnUnloadAbort );
							}
							// Add to list of active xhrs callbacks
							xhrCallbacks[ handle ] = callback;
						}
						xhr.onreadystatechange = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback(0,1);
					}
				}
			};
		}
	});
}
var fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
	rrun = /queueHooks$/,
	animationPrefilters = [ defaultPrefilter ],
	tweeners = {
		"*": [function( prop, value ) {
			var end, unit,
				tween = this.createTween( prop, value ),
				parts = rfxnum.exec( value ),
				target = tween.cur(),
				start = +target || 0,
				scale = 1,
				maxIterations = 20;

			if ( parts ) {
				end = +parts[2];
				unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );

				// We need to compute starting value
				if ( unit !== "px" && start ) {
					// Iteratively approximate from a nonzero starting point
					// Prefer the current property, because this process will be trivial if it uses the same units
					// Fallback to end or a simple constant
					start = jQuery.css( tween.elem, prop, true ) || end || 1;

					do {
						// If previous iteration zeroed out, double until we get *something*
						// Use a string for doubling factor so we don't accidentally see scale as unchanged below
						scale = scale || ".5";

						// Adjust and apply
						start = start / scale;
						jQuery.style( tween.elem, prop, start + unit );

					// Update scale, tolerating zero or NaN from tween.cur()
					// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
					} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
				}

				tween.unit = unit;
				tween.start = start;
				// If a +=/-= token was provided, we're doing a relative animation
				tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
			}
			return tween;
		}]
	};

// Animations created synchronously will run synchronously
function createFxNow() {
	setTimeout(function() {
		fxNow = undefined;
	}, 0 );
	return ( fxNow = jQuery.now() );
}

function createTweens( animation, props ) {
	jQuery.each( props, function( prop, value ) {
		var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
			index = 0,
			length = collection.length;
		for ( ; index < length; index++ ) {
			if ( collection[ index ].call( animation, prop, value ) ) {

				// we're done with this property
				return;
			}
		}
	});
}

function Animation( elem, properties, options ) {
	var result,
		index = 0,
		tweenerIndex = 0,
		length = animationPrefilters.length,
		deferred = jQuery.Deferred().always( function() {
			// don't match elem in the :animated selector
			delete tick.elem;
		}),
		tick = function() {
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
				// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length ; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ]);

			if ( percent < 1 && length ) {
				return remaining;
			} else {
				deferred.resolveWith( elem, [ animation ] );
				return false;
			}
		},
		animation = deferred.promise({
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, { specialEasing: {} }, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end, easing ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,
					// if we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;

				for ( ; index < length ; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// resolve when we played the last frame
				// otherwise, reject
				if ( gotoEnd ) {
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		}),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length ; index++ ) {
		result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			return result;
		}
	}

	createTweens( animation, props );

	if ( jQuery.isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	jQuery.fx.timer(
		jQuery.extend( tick, {
			anim: animation,
			queue: animation.opts.queue,
			elem: elem
		})
	);

	// attach callbacks from options
	return animation.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = jQuery.camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( jQuery.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// not quite $.extend, this wont overwrite keys already present.
			// also - reusing 'index' from above because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

jQuery.Animation = jQuery.extend( Animation, {

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.split(" ");
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			tweeners[ prop ] = tweeners[ prop ] || [];
			tweeners[ prop ].unshift( callback );
		}
	},

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			animationPrefilters.unshift( callback );
		} else {
			animationPrefilters.push( callback );
		}
	}
});

function defaultPrefilter( elem, props, opts ) {
	var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
		anim = this,
		style = elem.style,
		orig = {},
		handled = [],
		hidden = elem.nodeType && isHidden( elem );

	// handle queue: false promises
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always(function() {
			// doing this makes sure that the complete handler will be called
			// before this completes
			anim.always(function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			});
		});
	}

	// height/width overflow pass
	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
		// Make sure that nothing sneaks out
		// Record all 3 overflow attributes because IE does not
		// change the overflow attribute when overflowX and
		// overflowY are set to the same value
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Set display property to inline-block for height/width
		// animations on inline elements that are having width/height animated
		if ( jQuery.css( elem, "display" ) === "inline" &&
				jQuery.css( elem, "float" ) === "none" ) {

			// inline-level elements accept inline-block;
			// block-level elements need to be inline with layout
			if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
				style.display = "inline-block";

			} else {
				style.zoom = 1;
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		if ( !jQuery.support.shrinkWrapBlocks ) {
			anim.done(function() {
				style.overflow = opts.overflow[ 0 ];
				style.overflowX = opts.overflow[ 1 ];
				style.overflowY = opts.overflow[ 2 ];
			});
		}
	}


	// show/hide pass
	for ( index in props ) {
		value = props[ index ];
		if ( rfxtypes.exec( value ) ) {
			delete props[ index ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {
				continue;
			}
			handled.push( index );
		}
	}

	length = handled.length;
	if ( length ) {
		dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
		if ( "hidden" in dataShow ) {
			hidden = dataShow.hidden;
		}

		// store state if its toggle - enables .stop().toggle() to "reverse"
		if ( toggle ) {
			dataShow.hidden = !hidden;
		}
		if ( hidden ) {
			jQuery( elem ).show();
		} else {
			anim.done(function() {
				jQuery( elem ).hide();
			});
		}
		anim.done(function() {
			var prop;
			jQuery.removeData( elem, "fxshow", true );
			for ( prop in orig ) {
				jQuery.style( elem, prop, orig[ prop ] );
			}
		});
		for ( index = 0 ; index < length ; index++ ) {
			prop = handled[ index ];
			tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
			orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );

			if ( !( prop in dataShow ) ) {
				dataShow[ prop ] = tween.start;
				if ( hidden ) {
					tween.end = tween.start;
					tween.start = prop === "width" || prop === "height" ? 1 : 0;
				}
			}
		}
	}
}

function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || "swing";
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			if ( tween.elem[ tween.prop ] != null &&
				(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
				return tween.elem[ tween.prop ];
			}

			// passing any value as a 4th parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails
			// so, simple values such as "10px" are parsed to Float.
			// complex values such as "rotate(1rad)" are returned as is.
			result = jQuery.css( tween.elem, tween.prop, false, "" );
			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {
			// use step hook for back compat - use cssHook if its there - use .style if its
			// available and use plain properties where available
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes

Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ||
			// special check for .toggle( handler, handler, ... )
			( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
});

jQuery.fn.extend({
	fadeTo: function( speed, to, easing, callback ) {

		// show any hidden elements after setting opacity to 0
		return this.filter( isHidden ).css( "opacity", 0 ).show()

			// animate to the value specified
			.end().animate({ opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {
				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations resolve immediately
				if ( empty ) {
					anim.stop( true );
				}
			};

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each(function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = jQuery._data( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// start the next in the queue if the last step wasn't forced
			// timers currently will call their complete callbacks, which will dequeue
			// but only if they were gotoEnd
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		});
	}
});

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		attrs = { height: type },
		i = 0;

	// if we include width, step value is 1 to do all cssExpand values,
	// if we don't include width, step value is 2 to skip over Left and Right
	includeWidth = includeWidth? 1 : 0;
	for( ; i < 4 ; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show"),
	slideUp: genFx("hide"),
	slideToggle: genFx("toggle"),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
});

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			jQuery.isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
	};

	opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
		opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;

	// normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( jQuery.isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p*Math.PI ) / 2;
	}
};

jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
	var timer,
		timers = jQuery.timers,
		i = 0;

	fxNow = jQuery.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];
		// Checks the timer has not already been removed
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
		timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.interval = 13;

jQuery.fx.stop = function() {
	clearInterval( timerId );
	timerId = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,
	// Default speed
	_default: 400
};

// Back Compat <1.8 extension point
jQuery.fx.step = {};

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}
var rroot = /^(?:body|html)$/i;

jQuery.fn.offset = function( options ) {
	if ( arguments.length ) {
		return options === undefined ?
			this :
			this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
	}

	var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
		box = { top: 0, left: 0 },
		elem = this[ 0 ],
		doc = elem && elem.ownerDocument;

	if ( !doc ) {
		return;
	}

	if ( (body = doc.body) === elem ) {
		return jQuery.offset.bodyOffset( elem );
	}

	docElem = doc.documentElement;

	// Make sure it's not a disconnected DOM node
	if ( !jQuery.contains( docElem, elem ) ) {
		return box;
	}

	// If we don't have gBCR, just use 0,0 rather than error
	// BlackBerry 5, iOS 3 (original iPhone)
	if ( typeof elem.getBoundingClientRect !== "undefined" ) {
		box = elem.getBoundingClientRect();
	}
	win = getWindow( doc );
	clientTop  = docElem.clientTop  || body.clientTop  || 0;
	clientLeft = docElem.clientLeft || body.clientLeft || 0;
	scrollTop  = win.pageYOffset || docElem.scrollTop;
	scrollLeft = win.pageXOffset || docElem.scrollLeft;
	return {
		top: box.top  + scrollTop  - clientTop,
		left: box.left + scrollLeft - clientLeft
	};
};

jQuery.offset = {

	bodyOffset: function( body ) {
		var top = body.offsetTop,
			left = body.offsetLeft;

		if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
		}

		return { top: top, left: left };
	},

	setOffset: function( elem, options, i ) {
		var position = jQuery.css( elem, "position" );

		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		var curElem = jQuery( elem ),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css( elem, "top" ),
			curCSSLeft = jQuery.css( elem, "left" ),
			calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
			props = {}, curPosition = {}, curTop, curLeft;

		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;
		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};


jQuery.fn.extend({

	position: function() {
		if ( !this[0] ) {
			return;
		}

		var elem = this[0],

		// Get *real* offsetParent
		offsetParent = this.offsetParent(),

		// Get correct offsets
		offset       = this.offset(),
		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();

		// Subtract element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;

		// Add offsetParent borders
		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;

		// Subtract the two offsets
		return {
			top:  offset.top  - parentOffset.top,
			left: offset.left - parentOffset.left
		};
	},

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.body;
			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent || document.body;
		});
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
	var top = /Y/.test( prop );

	jQuery.fn[ method ] = function( val ) {
		return jQuery.access( this, function( elem, method, val ) {
			var win = getWindow( elem );

			if ( val === undefined ) {
				return win ? (prop in win) ? win[ prop ] :
					win.document.documentElement[ method ] :
					elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : jQuery( win ).scrollLeft(),
					 top ? val : jQuery( win ).scrollTop()
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length, null );
	};
});

function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
		// margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return jQuery.access( this, function( elem, type, value ) {
				var doc;

				if ( jQuery.isWindow( elem ) ) {
					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
					// isn't a whole lot we can do. See pull request at this URL for discussion:
					// https://github.com/jquery/jquery/pull/764
					return elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
					// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?
					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, value, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable, null );
		};
	});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
	define( "jquery", [], function () { return jQuery; } );
}

})( window );

//     Underscore.js 1.4.3
//     http://underscorejs.org
//     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
//     Underscore may be freely distributed under the MIT license.

(function() {

    // Baseline setup
    // --------------

    // Establish the root object, `window` in the browser, or `global` on the server.
    var root = this;

    // Save the previous value of the `_` variable.
    var previousUnderscore = root._;

    // Establish the object that gets returned to break out of a loop iteration.
    var breaker = {};

    // Save bytes in the minified (but not gzipped) version:
    var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

    // Create quick reference variables for speed access to core prototypes.
    var push             = ArrayProto.push,
        slice            = ArrayProto.slice,
        concat           = ArrayProto.concat,
        toString         = ObjProto.toString,
        hasOwnProperty   = ObjProto.hasOwnProperty;

    // All **ECMAScript 5** native function implementations that we hope to use
    // are declared here.
    var
        nativeForEach      = ArrayProto.forEach,
        nativeMap          = ArrayProto.map,
        nativeReduce       = ArrayProto.reduce,
        nativeReduceRight  = ArrayProto.reduceRight,
        nativeFilter       = ArrayProto.filter,
        nativeEvery        = ArrayProto.every,
        nativeSome         = ArrayProto.some,
        nativeIndexOf      = ArrayProto.indexOf,
        nativeLastIndexOf  = ArrayProto.lastIndexOf,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = FuncProto.bind;

    // Create a safe reference to the Underscore object for use below.
    var _ = function(obj) {
        if (obj instanceof _) return obj;
        if (!(this instanceof _)) return new _(obj);
        this._wrapped = obj;
    };

    // Export the Underscore object for **Node.js**, with
    // backwards-compatibility for the old `require()` API. If we're in
    // the browser, add `_` as a global object via a string identifier,
    // for Closure Compiler "advanced" mode.
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = _;
        }
        exports._ = _;
    } else {
        root._ = _;
    }

    // Current version.
    _.VERSION = '1.4.3';

    // Collection Functions
    // --------------------

    // The cornerstone, an `each` implementation, aka `forEach`.
    // Handles objects with the built-in `forEach`, arrays, and raw objects.
    // Delegates to **ECMAScript 5**'s native `forEach` if available.
    var each = _.each = _.forEach = function(obj, iterator, context) {
        if (obj == null) return;
        if (nativeForEach && obj.forEach === nativeForEach) {
            obj.forEach(iterator, context);
        } else if (obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (iterator.call(context, obj[i], i, obj) === breaker) return;
            }
        } else {
            for (var key in obj) {
                if (_.has(obj, key)) {
                    if (iterator.call(context, obj[key], key, obj) === breaker) return;
                }
            }
        }
    };

    // Return the results of applying the iterator to each element.
    // Delegates to **ECMAScript 5**'s native `map` if available.
    _.map = _.collect = function(obj, iterator, context) {
        var results = [];
        if (obj == null) return results;
        if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
        each(obj, function(value, index, list) {
            results[results.length] = iterator.call(context, value, index, list);
        });
        return results;
    };

    var reduceError = 'Reduce of empty array with no initial value';

    // **Reduce** builds up a single result from a list of values, aka `inject`,
    // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
    _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
        var initial = arguments.length > 2;
        if (obj == null) obj = [];
        if (nativeReduce && obj.reduce === nativeReduce) {
            if (context) iterator = _.bind(iterator, context);
            return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
        }
        each(obj, function(value, index, list) {
            if (!initial) {
                memo = value;
                initial = true;
            } else {
                memo = iterator.call(context, memo, value, index, list);
            }
        });
        if (!initial) throw new TypeError(reduceError);
        return memo;
    };

    // The right-associative version of reduce, also known as `foldr`.
    // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
    _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
        var initial = arguments.length > 2;
        if (obj == null) obj = [];
        if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
            if (context) iterator = _.bind(iterator, context);
            return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
        }
        var length = obj.length;
        if (length !== +length) {
            var keys = _.keys(obj);
            length = keys.length;
        }
        each(obj, function(value, index, list) {
            index = keys ? keys[--length] : --length;
            if (!initial) {
                memo = obj[index];
                initial = true;
            } else {
                memo = iterator.call(context, memo, obj[index], index, list);
            }
        });
        if (!initial) throw new TypeError(reduceError);
        return memo;
    };

    // Return the first value which passes a truth test. Aliased as `detect`.
    _.find = _.detect = function(obj, iterator, context) {
        var result;
        any(obj, function(value, index, list) {
            if (iterator.call(context, value, index, list)) {
                result = value;
                return true;
            }
        });
        return result;
    };

    // Return all the elements that pass a truth test.
    // Delegates to **ECMAScript 5**'s native `filter` if available.
    // Aliased as `select`.
    _.filter = _.select = function(obj, iterator, context) {
        var results = [];
        if (obj == null) return results;
        if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
        each(obj, function(value, index, list) {
            if (iterator.call(context, value, index, list)) results[results.length] = value;
        });
        return results;
    };

    // Return all the elements for which a truth test fails.
    _.reject = function(obj, iterator, context) {
        return _.filter(obj, function(value, index, list) {
            return !iterator.call(context, value, index, list);
        }, context);
    };

    // Determine whether all of the elements match a truth test.
    // Delegates to **ECMAScript 5**'s native `every` if available.
    // Aliased as `all`.
    _.every = _.all = function(obj, iterator, context) {
        iterator || (iterator = _.identity);
        var result = true;
        if (obj == null) return result;
        if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
        each(obj, function(value, index, list) {
            if (!(result = result && iterator.call(context, value, index, list))) return breaker;
        });
        return !!result;
    };

    // Determine if at least one element in the object matches a truth test.
    // Delegates to **ECMAScript 5**'s native `some` if available.
    // Aliased as `any`.
    var any = _.some = _.any = function(obj, iterator, context) {
        iterator || (iterator = _.identity);
        var result = false;
        if (obj == null) return result;
        if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
        each(obj, function(value, index, list) {
            if (result || (result = iterator.call(context, value, index, list))) return breaker;
        });
        return !!result;
    };

    // Determine if the array or object contains a given value (using `===`).
    // Aliased as `include`.
    _.contains = _.include = function(obj, target) {
        if (obj == null) return false;
        if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
        return any(obj, function(value) {
            return value === target;
        });
    };

    // Invoke a method (with arguments) on every item in a collection.
    _.invoke = function(obj, method) {
        var args = slice.call(arguments, 2);
        return _.map(obj, function(value) {
            return (_.isFunction(method) ? method : value[method]).apply(value, args);
        });
    };

    // Convenience version of a common use case of `map`: fetching a property.
    _.pluck = function(obj, key) {
        return _.map(obj, function(value){ return value[key]; });
    };

    // Convenience version of a common use case of `filter`: selecting only objects
    // with specific `key:value` pairs.
    _.where = function(obj, attrs) {
        if (_.isEmpty(attrs)) return [];
        return _.filter(obj, function(value) {
            for (var key in attrs) {
                if (attrs[key] !== value[key]) return false;
            }
            return true;
        });
    };

    // Return the maximum element or (element-based computation).
    // Can't optimize arrays of integers longer than 65,535 elements.
    // See: https://bugs.webkit.org/show_bug.cgi?id=80797
    _.max = function(obj, iterator, context) {
        if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
            return Math.max.apply(Math, obj);
        }
        if (!iterator && _.isEmpty(obj)) return -Infinity;
        var result = {computed : -Infinity, value: -Infinity};
        each(obj, function(value, index, list) {
            var computed = iterator ? iterator.call(context, value, index, list) : value;
            computed >= result.computed && (result = {value : value, computed : computed});
        });
        return result.value;
    };

    // Return the minimum element (or element-based computation).
    _.min = function(obj, iterator, context) {
        if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
            return Math.min.apply(Math, obj);
        }
        if (!iterator && _.isEmpty(obj)) return Infinity;
        var result = {computed : Infinity, value: Infinity};
        each(obj, function(value, index, list) {
            var computed = iterator ? iterator.call(context, value, index, list) : value;
            computed < result.computed && (result = {value : value, computed : computed});
        });
        return result.value;
    };

    // Shuffle an array.
    _.shuffle = function(obj) {
        var rand;
        var index = 0;
        var shuffled = [];
        each(obj, function(value) {
            rand = _.random(index++);
            shuffled[index - 1] = shuffled[rand];
            shuffled[rand] = value;
        });
        return shuffled;
    };

    // An internal function to generate lookup iterators.
    var lookupIterator = function(value) {
        return _.isFunction(value) ? value : function(obj){ return obj[value]; };
    };

    // Sort the object's values by a criterion produced by an iterator.
    _.sortBy = function(obj, value, context) {
        var iterator = lookupIterator(value);
        return _.pluck(_.map(obj, function(value, index, list) {
            return {
                value : value,
                index : index,
                criteria : iterator.call(context, value, index, list)
            };
        }).sort(function(left, right) {
                var a = left.criteria;
                var b = right.criteria;
                if (a !== b) {
                    if (a > b || a === void 0) return 1;
                    if (a < b || b === void 0) return -1;
                }
                return left.index < right.index ? -1 : 1;
            }), 'value');
    };

    // An internal function used for aggregate "group by" operations.
    var group = function(obj, value, context, behavior) {
        var result = {};
        var iterator = lookupIterator(value || _.identity);
        each(obj, function(value, index) {
            var key = iterator.call(context, value, index, obj);
            behavior(result, key, value);
        });
        return result;
    };

    // Groups the object's values by a criterion. Pass either a string attribute
    // to group by, or a function that returns the criterion.
    _.groupBy = function(obj, value, context) {
        return group(obj, value, context, function(result, key, value) {
            (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
        });
    };

    // Counts instances of an object that group by a certain criterion. Pass
    // either a string attribute to count by, or a function that returns the
    // criterion.
    _.countBy = function(obj, value, context) {
        return group(obj, value, context, function(result, key) {
            if (!_.has(result, key)) result[key] = 0;
            result[key]++;
        });
    };

    // Use a comparator function to figure out the smallest index at which
    // an object should be inserted so as to maintain order. Uses binary search.
    _.sortedIndex = function(array, obj, iterator, context) {
        iterator = iterator == null ? _.identity : lookupIterator(iterator);
        var value = iterator.call(context, obj);
        var low = 0, high = array.length;
        while (low < high) {
            var mid = (low + high) >>> 1;
            iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
        }
        return low;
    };

    // Safely convert anything iterable into a real, live array.
    _.toArray = function(obj) {
        if (!obj) return [];
        if (_.isArray(obj)) return slice.call(obj);
        if (obj.length === +obj.length) return _.map(obj, _.identity);
        return _.values(obj);
    };

    // Return the number of elements in an object.
    _.size = function(obj) {
        if (obj == null) return 0;
        return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
    };

    // Array Functions
    // ---------------

    // Get the first element of an array. Passing **n** will return the first N
    // values in the array. Aliased as `head` and `take`. The **guard** check
    // allows it to work with `_.map`.
    _.first = _.head = _.take = function(array, n, guard) {
        if (array == null) return void 0;
        return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
    };

    // Returns everything but the last entry of the array. Especially useful on
    // the arguments object. Passing **n** will return all the values in
    // the array, excluding the last N. The **guard** check allows it to work with
    // `_.map`.
    _.initial = function(array, n, guard) {
        return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
    };

    // Get the last element of an array. Passing **n** will return the last N
    // values in the array. The **guard** check allows it to work with `_.map`.
    _.last = function(array, n, guard) {
        if (array == null) return void 0;
        if ((n != null) && !guard) {
            return slice.call(array, Math.max(array.length - n, 0));
        } else {
            return array[array.length - 1];
        }
    };

    // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
    // Especially useful on the arguments object. Passing an **n** will return
    // the rest N values in the array. The **guard**
    // check allows it to work with `_.map`.
    _.rest = _.tail = _.drop = function(array, n, guard) {
        return slice.call(array, (n == null) || guard ? 1 : n);
    };

    // Trim out all falsy values from an array.
    _.compact = function(array) {
        return _.filter(array, _.identity);
    };

    // Internal implementation of a recursive `flatten` function.
    var flatten = function(input, shallow, output) {
        each(input, function(value) {
            if (_.isArray(value)) {
                shallow ? push.apply(output, value) : flatten(value, shallow, output);
            } else {
                output.push(value);
            }
        });
        return output;
    };

    // Return a completely flattened version of an array.
    _.flatten = function(array, shallow) {
        return flatten(array, shallow, []);
    };

    // Return a version of the array that does not contain the specified value(s).
    _.without = function(array) {
        return _.difference(array, slice.call(arguments, 1));
    };

    // Produce a duplicate-free version of the array. If the array has already
    // been sorted, you have the option of using a faster algorithm.
    // Aliased as `unique`.
    _.uniq = _.unique = function(array, isSorted, iterator, context) {
        if (_.isFunction(isSorted)) {
            context = iterator;
            iterator = isSorted;
            isSorted = false;
        }
        var initial = iterator ? _.map(array, iterator, context) : array;
        var results = [];
        var seen = [];
        each(initial, function(value, index) {
            if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
                seen.push(value);
                results.push(array[index]);
            }
        });
        return results;
    };

    // Produce an array that contains the union: each distinct element from all of
    // the passed-in arrays.
    _.union = function() {
        return _.uniq(concat.apply(ArrayProto, arguments));
    };

    // Produce an array that contains every item shared between all the
    // passed-in arrays.
    _.intersection = function(array) {
        var rest = slice.call(arguments, 1);
        return _.filter(_.uniq(array), function(item) {
            return _.every(rest, function(other) {
                return _.indexOf(other, item) >= 0;
            });
        });
    };

    // Take the difference between one array and a number of other arrays.
    // Only the elements present in just the first array will remain.
    _.difference = function(array) {
        var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
        return _.filter(array, function(value){ return !_.contains(rest, value); });
    };

    // Zip together multiple lists into a single array -- elements that share
    // an index go together.
    _.zip = function() {
        var args = slice.call(arguments);
        var length = _.max(_.pluck(args, 'length'));
        var results = new Array(length);
        for (var i = 0; i < length; i++) {
            results[i] = _.pluck(args, "" + i);
        }
        return results;
    };

    // Converts lists into objects. Pass either a single array of `[key, value]`
    // pairs, or two parallel arrays of the same length -- one of keys, and one of
    // the corresponding values.
    _.object = function(list, values) {
        if (list == null) return {};
        var result = {};
        for (var i = 0, l = list.length; i < l; i++) {
            if (values) {
                result[list[i]] = values[i];
            } else {
                result[list[i][0]] = list[i][1];
            }
        }
        return result;
    };

    // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
    // we need this function. Return the position of the first occurrence of an
    // item in an array, or -1 if the item is not included in the array.
    // Delegates to **ECMAScript 5**'s native `indexOf` if available.
    // If the array is large and already in sort order, pass `true`
    // for **isSorted** to use binary search.
    _.indexOf = function(array, item, isSorted) {
        if (array == null) return -1;
        var i = 0, l = array.length;
        if (isSorted) {
            if (typeof isSorted == 'number') {
                i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
            } else {
                i = _.sortedIndex(array, item);
                return array[i] === item ? i : -1;
            }
        }
        if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
        for (; i < l; i++) if (array[i] === item) return i;
        return -1;
    };

    // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
    _.lastIndexOf = function(array, item, from) {
        if (array == null) return -1;
        var hasIndex = from != null;
        if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
            return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
        }
        var i = (hasIndex ? from : array.length);
        while (i--) if (array[i] === item) return i;
        return -1;
    };

    // Generate an integer Array containing an arithmetic progression. A port of
    // the native Python `range()` function. See
    // [the Python documentation](http://docs.python.org/library/functions.html#range).
    _.range = function(start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = arguments[2] || 1;

        var len = Math.max(Math.ceil((stop - start) / step), 0);
        var idx = 0;
        var range = new Array(len);

        while(idx < len) {
            range[idx++] = start;
            start += step;
        }

        return range;
    };

    // Function (ahem) Functions
    // ------------------

    // Reusable constructor function for prototype setting.
    var ctor = function(){};

    // Create a function bound to a given object (assigning `this`, and arguments,
    // optionally). Binding with arguments is also known as `curry`.
    // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
    // We check for `func.bind` first, to fail fast when `func` is undefined.
    _.bind = function(func, context) {
        var args, bound;
        if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
        if (!_.isFunction(func)) throw new TypeError;
        args = slice.call(arguments, 2);
        return bound = function() {
            if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
            ctor.prototype = func.prototype;
            var self = new ctor;
            ctor.prototype = null;
            var result = func.apply(self, args.concat(slice.call(arguments)));
            if (Object(result) === result) return result;
            return self;
        };
    };

    // Bind all of an object's methods to that object. Useful for ensuring that
    // all callbacks defined on an object belong to it.
    _.bindAll = function(obj) {
        var funcs = slice.call(arguments, 1);
        if (funcs.length == 0) funcs = _.functions(obj);
        each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
        return obj;
    };

    // Memoize an expensive function by storing its results.
    _.memoize = function(func, hasher) {
        var memo = {};
        hasher || (hasher = _.identity);
        return function() {
            var key = hasher.apply(this, arguments);
            return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
        };
    };

    // Delays a function for the given number of milliseconds, and then calls
    // it with the arguments supplied.
    _.delay = function(func, wait) {
        var args = slice.call(arguments, 2);
        return setTimeout(function(){ return func.apply(null, args); }, wait);
    };

    // Defers a function, scheduling it to run after the current call stack has
    // cleared.
    _.defer = function(func) {
        return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
    };

    // Returns a function, that, when invoked, will only be triggered at most once
    // during a given window of time.
    _.throttle = function(func, wait) {
        var context, args, timeout, result;
        var previous = 0;
        var later = function() {
            previous = new Date;
            timeout = null;
            result = func.apply(context, args);
        };
        return function() {
            var now = new Date;
            var remaining = wait - (now - previous);
            context = this;
            args = arguments;
            if (remaining <= 0) {
                clearTimeout(timeout);
                timeout = null;
                previous = now;
                result = func.apply(context, args);
            } else if (!timeout) {
                timeout = setTimeout(later, remaining);
            }
            return result;
        };
    };

    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds. If `immediate` is passed, trigger the function on the
    // leading edge, instead of the trailing.
    _.debounce = function(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) result = func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) result = func.apply(context, args);
            return result;
        };
    };

    // Returns a function that will be executed at most one time, no matter how
    // often you call it. Useful for lazy initialization.
    _.once = function(func) {
        var ran = false, memo;
        return function() {
            if (ran) return memo;
            ran = true;
            memo = func.apply(this, arguments);
            func = null;
            return memo;
        };
    };

    // Returns the first function passed as an argument to the second,
    // allowing you to adjust arguments, run code before and after, and
    // conditionally execute the original function.
    _.wrap = function(func, wrapper) {
        return function() {
            var args = [func];
            push.apply(args, arguments);
            return wrapper.apply(this, args);
        };
    };

    // Returns a function that is the composition of a list of functions, each
    // consuming the return value of the function that follows.
    _.compose = function() {
        var funcs = arguments;
        return function() {
            var args = arguments;
            for (var i = funcs.length - 1; i >= 0; i--) {
                args = [funcs[i].apply(this, args)];
            }
            return args[0];
        };
    };

    // Returns a function that will only be executed after being called N times.
    _.after = function(times, func) {
        if (times <= 0) return func();
        return function() {
            if (--times < 1) {
                return func.apply(this, arguments);
            }
        };
    };

    // Object Functions
    // ----------------

    // Retrieve the names of an object's properties.
    // Delegates to **ECMAScript 5**'s native `Object.keys`
    _.keys = nativeKeys || function(obj) {
        if (obj !== Object(obj)) throw new TypeError('Invalid object');
        var keys = [];
        for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
        return keys;
    };

    // Retrieve the values of an object's properties.
    _.values = function(obj) {
        var values = [];
        for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
        return values;
    };

    // Convert an object into a list of `[key, value]` pairs.
    _.pairs = function(obj) {
        var pairs = [];
        for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
        return pairs;
    };

    // Invert the keys and values of an object. The values must be serializable.
    _.invert = function(obj) {
        var result = {};
        for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
        return result;
    };

    // Return a sorted list of the function names available on the object.
    // Aliased as `methods`
    _.functions = _.methods = function(obj) {
        var names = [];
        for (var key in obj) {
            if (_.isFunction(obj[key])) names.push(key);
        }
        return names.sort();
    };

    // Extend a given object with all the properties in passed-in object(s).
    _.extend = function(obj) {
        each(slice.call(arguments, 1), function(source) {
            if (source) {
                for (var prop in source) {
                    obj[prop] = source[prop];
                }
            }
        });
        return obj;
    };

    // Return a copy of the object only containing the whitelisted properties.
    _.pick = function(obj) {
        var copy = {};
        var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
        each(keys, function(key) {
            if (key in obj) copy[key] = obj[key];
        });
        return copy;
    };

    // Return a copy of the object without the blacklisted properties.
    _.omit = function(obj) {
        var copy = {};
        var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
        for (var key in obj) {
            if (!_.contains(keys, key)) copy[key] = obj[key];
        }
        return copy;
    };

    // Fill in a given object with default properties.
    _.defaults = function(obj) {
        each(slice.call(arguments, 1), function(source) {
            if (source) {
                for (var prop in source) {
                    if (obj[prop] == null) obj[prop] = source[prop];
                }
            }
        });
        return obj;
    };

    // Create a (shallow-cloned) duplicate of an object.
    _.clone = function(obj) {
        if (!_.isObject(obj)) return obj;
        return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
    };

    // Invokes interceptor with the obj, and then returns obj.
    // The primary purpose of this method is to "tap into" a method chain, in
    // order to perform operations on intermediate results within the chain.
    _.tap = function(obj, interceptor) {
        interceptor(obj);
        return obj;
    };

    // Internal recursive comparison function for `isEqual`.
    var eq = function(a, b, aStack, bStack) {
        // Identical objects are equal. `0 === -0`, but they aren't identical.
        // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
        if (a === b) return a !== 0 || 1 / a == 1 / b;
        // A strict comparison is necessary because `null == undefined`.
        if (a == null || b == null) return a === b;
        // Unwrap any wrapped objects.
        if (a instanceof _) a = a._wrapped;
        if (b instanceof _) b = b._wrapped;
        // Compare `[[Class]]` names.
        var className = toString.call(a);
        if (className != toString.call(b)) return false;
        switch (className) {
            // Strings, numbers, dates, and booleans are compared by value.
            case '[object String]':
                // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
                // equivalent to `new String("5")`.
                return a == String(b);
            case '[object Number]':
                // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
                // other numeric values.
                return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
            case '[object Date]':
            case '[object Boolean]':
                // Coerce dates and booleans to numeric primitive values. Dates are compared by their
                // millisecond representations. Note that invalid dates with millisecond representations
                // of `NaN` are not equivalent.
                return +a == +b;
            // RegExps are compared by their source patterns and flags.
            case '[object RegExp]':
                return a.source == b.source &&
                    a.global == b.global &&
                    a.multiline == b.multiline &&
                    a.ignoreCase == b.ignoreCase;
        }
        if (typeof a != 'object' || typeof b != 'object') return false;
        // Assume equality for cyclic structures. The algorithm for detecting cyclic
        // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
        var length = aStack.length;
        while (length--) {
            // Linear search. Performance is inversely proportional to the number of
            // unique nested structures.
            if (aStack[length] == a) return bStack[length] == b;
        }
        // Add the first object to the stack of traversed objects.
        aStack.push(a);
        bStack.push(b);
        var size = 0, result = true;
        // Recursively compare objects and arrays.
        if (className == '[object Array]') {
            // Compare array lengths to determine if a deep comparison is necessary.
            size = a.length;
            result = size == b.length;
            if (result) {
                // Deep compare the contents, ignoring non-numeric properties.
                while (size--) {
                    if (!(result = eq(a[size], b[size], aStack, bStack))) break;
                }
            }
        } else {
            // Objects with different constructors are not equivalent, but `Object`s
            // from different frames are.
            var aCtor = a.constructor, bCtor = b.constructor;
            if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
                _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
                return false;
            }
            // Deep compare objects.
            for (var key in a) {
                if (_.has(a, key)) {
                    // Count the expected number of properties.
                    size++;
                    // Deep compare each member.
                    if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
                }
            }
            // Ensure that both objects contain the same number of properties.
            if (result) {
                for (key in b) {
                    if (_.has(b, key) && !(size--)) break;
                }
                result = !size;
            }
        }
        // Remove the first object from the stack of traversed objects.
        aStack.pop();
        bStack.pop();
        return result;
    };

    // Perform a deep comparison to check if two objects are equal.
    _.isEqual = function(a, b) {
        return eq(a, b, [], []);
    };

    // Is a given array, string, or object empty?
    // An "empty" object has no enumerable own-properties.
    _.isEmpty = function(obj) {
        if (obj == null) return true;
        if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
        for (var key in obj) if (_.has(obj, key)) return false;
        return true;
    };

    // Is a given value a DOM element?
    _.isElement = function(obj) {
        return !!(obj && obj.nodeType === 1);
    };

    // Is a given value an array?
    // Delegates to ECMA5's native Array.isArray
    _.isArray = nativeIsArray || function(obj) {
        return toString.call(obj) == '[object Array]';
    };

    // Is a given variable an object?
    _.isObject = function(obj) {
        return obj === Object(obj);
    };

    // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
    each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
        _['is' + name] = function(obj) {
            return toString.call(obj) == '[object ' + name + ']';
        };
    });

    // Define a fallback version of the method in browsers (ahem, IE), where
    // there isn't any inspectable "Arguments" type.
    if (!_.isArguments(arguments)) {
        _.isArguments = function(obj) {
            return !!(obj && _.has(obj, 'callee'));
        };
    }

    // Optimize `isFunction` if appropriate.
    if (typeof (/./) !== 'function') {
        _.isFunction = function(obj) {
            return typeof obj === 'function';
        };
    }

    // Is a given object a finite number?
    _.isFinite = function(obj) {
        return isFinite(obj) && !isNaN(parseFloat(obj));
    };

    // Is the given value `NaN`? (NaN is the only number which does not equal itself).
    _.isNaN = function(obj) {
        return _.isNumber(obj) && obj != +obj;
    };

    // Is a given value a boolean?
    _.isBoolean = function(obj) {
        return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
    };

    // Is a given value equal to null?
    _.isNull = function(obj) {
        return obj === null;
    };

    // Is a given variable undefined?
    _.isUndefined = function(obj) {
        return obj === void 0;
    };

    // Shortcut function for checking if an object has a given property directly
    // on itself (in other words, not on a prototype).
    _.has = function(obj, key) {
        return hasOwnProperty.call(obj, key);
    };

    // Utility Functions
    // -----------------

    // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
    // previous owner. Returns a reference to the Underscore object.
    _.noConflict = function() {
        root._ = previousUnderscore;
        return this;
    };

    // Keep the identity function around for default iterators.
    _.identity = function(value) {
        return value;
    };

    // Run a function **n** times.
    _.times = function(n, iterator, context) {
        var accum = Array(n);
        for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
        return accum;
    };

    // Return a random integer between min and max (inclusive).
    _.random = function(min, max) {
        if (max == null) {
            max = min;
            min = 0;
        }
        return min + (0 | Math.random() * (max - min + 1));
    };

    // List of HTML entities for escaping.
    var entityMap = {
        escape: {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#x27;',
            '/': '&#x2F;'
        }
    };
    entityMap.unescape = _.invert(entityMap.escape);

    // Regexes containing the keys and values listed immediately above.
    var entityRegexes = {
        escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
        unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
    };

    // Functions for escaping and unescaping strings to/from HTML interpolation.
    _.each(['escape', 'unescape'], function(method) {
        _[method] = function(string) {
            if (string == null) return '';
            return ('' + string).replace(entityRegexes[method], function(match) {
                return entityMap[method][match];
            });
        };
    });

    // If the value of the named property is a function then invoke it;
    // otherwise, return it.
    _.result = function(object, property) {
        if (object == null) return null;
        var value = object[property];
        return _.isFunction(value) ? value.call(object) : value;
    };

    // Add your own custom functions to the Underscore object.
    _.mixin = function(obj) {
        each(_.functions(obj), function(name){
            var func = _[name] = obj[name];
            _.prototype[name] = function() {
                var args = [this._wrapped];
                push.apply(args, arguments);
                return result.call(this, func.apply(_, args));
            };
        });
    };

    // Generate a unique integer id (unique within the entire client session).
    // Useful for temporary DOM ids.
    var idCounter = 0;
    _.uniqueId = function(prefix) {
        var id = '' + ++idCounter;
        return prefix ? prefix + id : id;
    };

    // By default, Underscore uses ERB-style template delimiters, change the
    // following template settings to use alternative delimiters.
    _.templateSettings = {
        evaluate    : /<%([\s\S]+?)%>/g,
        interpolate : /<%=([\s\S]+?)%>/g,
        escape      : /<%-([\s\S]+?)%>/g
    };

    // When customizing `templateSettings`, if you don't want to define an
    // interpolation, evaluation or escaping regex, we need one that is
    // guaranteed not to match.
    var noMatch = /(.)^/;

    // Certain characters need to be escaped so that they can be put into a
    // string literal.
    var escapes = {
        "'":      "'",
        '\\':     '\\',
        '\r':     'r',
        '\n':     'n',
        '\t':     't',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
    };

    var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;

    // JavaScript micro-templating, similar to John Resig's implementation.
    // Underscore templating handles arbitrary delimiters, preserves whitespace,
    // and correctly escapes quotes within interpolated code.
    _.template = function(text, data, settings) {
        settings = _.defaults({}, settings, _.templateSettings);

        // Combine delimiters into one regular expression via alternation.
        var matcher = new RegExp([
            (settings.escape || noMatch).source,
            (settings.interpolate || noMatch).source,
            (settings.evaluate || noMatch).source
        ].join('|') + '|$', 'g');

        // Compile the template source, escaping string literals appropriately.
        var index = 0;
        var source = "__p+='";
        text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
            source += text.slice(index, offset)
                .replace(escaper, function(match) { return '\\' + escapes[match]; });

            if (escape) {
                source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
            }
            if (interpolate) {
                source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
            }
            if (evaluate) {
                source += "';\n" + evaluate + "\n__p+='";
            }
            index = offset + match.length;
            return match;
        });
        source += "';\n";

        // If a variable is not specified, place data values in local scope.
        if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

        source = "var __t,__p='',__j=Array.prototype.join," +
            "print=function(){__p+=__j.call(arguments,'');};\n" +
            source + "return __p;\n";

        try {
            var render = new Function(settings.variable || 'obj', '_', source);
        } catch (e) {
            e.source = source;
            throw e;
        }

        if (data) return render(data, _);
        var template = function(data) {
            return render.call(this, data, _);
        };

        // Provide the compiled function source as a convenience for precompilation.
        template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';

        return template;
    };

    // Add a "chain" function, which will delegate to the wrapper.
    _.chain = function(obj) {
        return _(obj).chain();
    };

    // OOP
    // ---------------
    // If Underscore is called as a function, it returns a wrapped object that
    // can be used OO-style. This wrapper holds altered versions of all the
    // underscore functions. Wrapped objects may be chained.

    // Helper function to continue chaining intermediate results.
    var result = function(obj) {
        return this._chain ? _(obj).chain() : obj;
    };

    // Add all of the Underscore functions to the wrapper object.
    _.mixin(_);

    // Add all mutator Array functions to the wrapper.
    each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
        var method = ArrayProto[name];
        _.prototype[name] = function() {
            var obj = this._wrapped;
            method.apply(obj, arguments);
            if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
            return result.call(this, obj);
        };
    });

    // Add all accessor Array functions to the wrapper.
    each(['concat', 'join', 'slice'], function(name) {
        var method = ArrayProto[name];
        _.prototype[name] = function() {
            return result.call(this, method.apply(this._wrapped, arguments));
        };
    });

    _.extend(_.prototype, {

        // Start chaining a wrapped Underscore object.
        chain: function() {
            this._chain = true;
            return this;
        },

        // Extracts the result from a wrapped and chained object.
        value: function() {
            return this._wrapped;
        }

    });

    // AMD define happens at the end for compatibility with AMD loaders
    // that don't enforce next-turn semantics on modules.
    if (typeof define === 'function' && define.amd) {
        define('underscore',[], function() {
            return _;
        });
    }

}).call(this);
//     Backbone.js 0.9.2

//     (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

//     2 lines updated to reflect changes in github 0.9.2
//     to find, search 'github.com'
//     enables hashChange: false in Backbone.history.start()

(function(root, factory) {
  // Set up Backbone appropriately for the environment.
  if (typeof exports !== 'undefined') {
    // Node/CommonJS, no need for jQuery in that case.
    factory(root, exports, require('underscore'));
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define('backbone',['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });
  } else {
    // Browser globals
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender));
  }
}(this, function(root, Backbone, _, $) {

  // Initial Setup
  // -------------

  // Save the previous value of the `Backbone` variable, so that it can be
  // restored later on, if `noConflict` is used.
  var previousBackbone = root.Backbone;

  // Create a local reference to slice/splice.
  var slice = Array.prototype.slice;
  var splice = Array.prototype.splice;

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '0.9.2';

  // Set the JavaScript library that will be used for DOM manipulation and
  // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery,
  // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an
  // alternate JavaScript library (or a mock library for testing your views
  // outside of a browser).
  Backbone.setDomLibrary = function(lib) {
    $ = lib;
  };

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return Backbone;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Backbone.Events
  // -----------------

  // Regular expression used to split event strings
  var eventSplitter = /\s+/;

  // A module that can be mixed in to *any object* in order to provide it with
  // custom events. You may bind with `on` or remove with `off` callback functions
  // to an event; trigger`-ing an event fires all callbacks in succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.on('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  var Events = Backbone.Events = {

    // Bind one or more space separated events, `events`, to a `callback`
    // function. Passing `"all"` will bind the callback to all events fired.
    on: function(events, callback, context) {

      var calls, event, node, tail, list;
      if (!callback) return this;
      events = events.split(eventSplitter);
      calls = this._callbacks || (this._callbacks = {});

      // Create an immutable callback list, allowing traversal during
      // modification.  The tail is an empty object that will always be used
      // as the next node.
      while (event = events.shift()) {
        list = calls[event];
        node = list ? list.tail : {};
        node.next = tail = {};
        node.context = context;
        node.callback = callback;
        calls[event] = {tail: tail, next: list ? list.next : node};
      }

      return this;
    },

    // Remove one or many callbacks. If `context` is null, removes all callbacks
    // with that function. If `callback` is null, removes all callbacks for the
    // event. If `events` is null, removes all bound callbacks for all events.
    off: function(events, callback, context) {
      var event, calls, node, tail, cb, ctx;

      // No events, or removing *all* events.
      if (!(calls = this._callbacks)) return;
      if (!(events || callback || context)) {
        delete this._callbacks;
        return this;
      }

      // Loop through the listed events and contexts, splicing them out of the
      // linked list of callbacks if appropriate.
      events = events ? events.split(eventSplitter) : _.keys(calls);
      while (event = events.shift()) {
        node = calls[event];
        delete calls[event];
        if (!node || !(callback || context)) continue;
        // Create a new list, omitting the indicated callbacks.
        tail = node.tail;
        while ((node = node.next) !== tail) {
          cb = node.callback;
          ctx = node.context;
          if ((callback && cb !== callback) || (context && ctx !== context)) {
            this.on(event, cb, ctx);
          }
        }
      }

      return this;
    },

    // Trigger one or many events, firing all bound callbacks. Callbacks are
    // passed the same arguments as `trigger` is, apart from the event name
    // (unless you're listening on `"all"`, which will cause your callback to
    // receive the true name of the event as the first argument).
    trigger: function(events) {
      var event, node, calls, tail, args, all, rest;
      if (!(calls = this._callbacks)) return this;
      all = calls.all;
      events = events.split(eventSplitter);
      rest = slice.call(arguments, 1);

      // For each event, walk through the linked list of callbacks twice,
      // first to trigger the event, then to trigger any `"all"` callbacks.
      while (event = events.shift()) {
        if (node = calls[event]) {
          tail = node.tail;
          while ((node = node.next) !== tail) {
            node.callback.apply(node.context || this, rest);
          }
        }
        if (node = all) {
          tail = node.tail;
          args = [event].concat(rest);
          while ((node = node.next) !== tail) {
            node.callback.apply(node.context || this, args);
          }
        }
      }

      return this;
    }

  };

  // Aliases for backwards compatibility.
  Events.bind   = Events.on;
  Events.unbind = Events.off;

  // Backbone.Model
  // --------------

  // Create a new model, with defined attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    var defaults;
    attributes || (attributes = {});
    if (options && options.parse) attributes = this.parse(attributes);
    if (defaults = getValue(this, 'defaults')) {
      attributes = _.extend({}, defaults, attributes);
    }
    if (options && options.collection) this.collection = options.collection;
    this.attributes = {};
    this._escapedAttributes = {};
    this.cid = _.uniqueId('c');
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this.set(attributes, {silent: true});
    // Reset change tracking.
    this.changed = {};
    this._silent = {};
    this._pending = {};
    this._previousAttributes = _.clone(this.attributes);
    this.initialize.apply(this, arguments);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Model.prototype, Events, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // A hash of attributes that have silently changed since the last time
    // `change` was called.  Will become pending attributes on the next call.
    _silent: null,

    // A hash of attributes that have changed since the last `'change'` event
    // began.
    _pending: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      var html;
      if (html = this._escapedAttributes[attr]) return html;
      var val = this.get(attr);
      return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Set a hash of model attributes on the object, firing `"change"` unless
    // you choose to silence it.
    set: function(key, value, options) {
      var attrs, attr, val;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
      } else {
        attrs = {};
        attrs[key] = value;
      }

      // Extract attributes and options.
      options || (options = {});
      if (!attrs) return this;
      if (attrs instanceof Model) attrs = attrs.attributes;
      if (options.unset) for (attr in attrs) attrs[attr] = void 0;

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Check for changes of `id`.
      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

      var changes = options.changes = {};
      var now = this.attributes;
      var escaped = this._escapedAttributes;
      var prev = this._previousAttributes || {};

      // For each `set` attribute...
      for (attr in attrs) {
        val = attrs[attr];

        // If the new and current value differ, record the change.
        if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
          delete escaped[attr];
          (options.silent ? this._silent : changes)[attr] = true;
        }

        // Update or delete the current value.
        options.unset ? delete now[attr] : now[attr] = val;

        // If the new and previous value differ, record the change.  If not,
        // then remove changes for this attribute.
        if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
          this.changed[attr] = val;
          if (!options.silent) this._pending[attr] = true;
        } else {
          delete this.changed[attr];
          delete this._pending[attr];
        }
      }

      // Fire the `"change"` events.
      if (!options.silent) this.change(options);
      return this;
    },

    // Remove an attribute from the model, firing `"change"` unless you choose
    // to silence it. `unset` is a noop if the attribute doesn't exist.
    unset: function(attr, options) {
      (options || (options = {})).unset = true;
      return this.set(attr, null, options);
    },

    // Clear all attributes on the model, firing `"change"` unless you choose
    // to silence it.
    clear: function(options) {
      (options || (options = {})).unset = true;
      return this.set(_.clone(this.attributes), options);
    },

    // Fetch the model from the server. If the server's representation of the
    // model differs from its current attributes, they will be overriden,
    // triggering a `"change"` event.
    fetch: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        if (!model.set(model.parse(resp, xhr), options)) return false;
        if (success) success(model, resp);
      };
      options.error = Backbone.wrapError(options.error, model, options);
      return (this.sync || Backbone.sync).call(this, 'read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, value, options) {
      var attrs, current;

      // Handle both `("key", value)` and `({key: value})` -style calls.
      if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
      } else {
        attrs = {};
        attrs[key] = value;
      }
      options = options ? _.clone(options) : {};

      // If we're "wait"-ing to set changed attributes, validate early.
      if (options.wait) {
        if (!this._validate(attrs, options)) return false;
        current = _.clone(this.attributes);
      }

      // Regular saves `set` attributes before persisting to the server.
      var silentOptions = _.extend({}, options, {silent: true});
      if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        var serverAttrs = model.parse(resp, xhr);
        if (options.wait) {
          delete options.wait;
          serverAttrs = _.extend(attrs || {}, serverAttrs);
        }
        if (!model.set(serverAttrs, options)) return false;
        if (success) {
          success(model, resp);
        } else {
          model.trigger('sync', model, resp, options);
        }
      };

      // Finish configuring and sending the Ajax request.
      options.error = Backbone.wrapError(options.error, model, options);
      var method = this.isNew() ? 'create' : 'update';
      var xhr = (this.sync || Backbone.sync).call(this, method, this, options);
      if (options.wait) this.set(current, silentOptions);
      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;

      var triggerDestroy = function() {
        model.trigger('destroy', model, model.collection, options);
      };

      if (this.isNew()) {
        triggerDestroy();
        return false;
      }

      options.success = function(resp) {
        if (options.wait) triggerDestroy();
        if (success) {
          success(model, resp);
        } else {
          model.trigger('sync', model, resp, options);
        }
      };

      options.error = Backbone.wrapError(options.error, model, options);
      var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
      if (!options.wait) triggerDestroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
      if (this.isNew()) return base;
      return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, xhr) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      return new this.constructor(this.attributes);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return this.id == null;
    },

    // Call this method to manually fire a `"change"` event for this model and
    // a `"change:attribute"` event for each changed attribute.
    // Calling this will cause all objects observing the model to update.
    change: function(options) {
      options || (options = {});
      var changing = this._changing;
      this._changing = true;

      // Silent changes become pending changes.
      for (var attr in this._silent) this._pending[attr] = true;

      // Silent changes are triggered.
      var changes = _.extend({}, options.changes, this._silent);
      this._silent = {};
      for (var attr in changes) {
        this.trigger('change:' + attr, this, this.get(attr), options);
      }
      if (changing) return this;

      // Continue firing `"change"` events while there are pending changes.
      while (!_.isEmpty(this._pending)) {
        this._pending = {};
        this.trigger('change', this, options);
        // Pending and silent changes still remain.
        for (var attr in this.changed) {
          if (this._pending[attr] || this._silent[attr]) continue;
          delete this.changed[attr];
        }
        this._previousAttributes = _.clone(this.attributes);
      }

      this._changing = false;
      return this;
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (!arguments.length) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var val, changed = false, old = this._previousAttributes;
      for (var attr in diff) {
        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
        (changed || (changed = {}))[attr] = val;
      }
      return changed;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (!arguments.length || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Check if the model is currently in a valid state. It's only possible to
    // get into an *invalid* state if you're using silent changes.
    isValid: function() {
      return !this.validate(this.attributes);
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. If a specific `error` callback has
    // been passed, call that instead of firing the general `"error"` event.
    _validate: function(attrs, options) {
      if (options.silent || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validate(attrs, options);
      if (!error) return true;
      if (options && options.error) {
        options.error(this, error, options);
      } else {
        this.trigger('error', this, error, options);
      }
      return false;
    }

  });

  // Backbone.Collection
  // -------------------

  // Provides a standard collection class for our sets of models, ordered
  // or unordered. If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  var Collection = Backbone.Collection = function(models, options) {
    options || (options = {});
    if (options.model) this.model = options.model;
    if (options.comparator) this.comparator = options.comparator;
    this._reset();
    this.initialize.apply(this, arguments);
    if (models) this.reset(models, {silent: true, parse: options.parse});
  };

  // Define the Collection's inheritable methods.
  _.extend(Collection.prototype, Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model: Model,

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON: function(options) {
      return this.map(function(model){ return model.toJSON(options); });
    },

    // Add a model, or list of models to the set. Pass **silent** to avoid
    // firing the `add` event for every new model.
    add: function(models, options) {
      var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
      options || (options = {});
      models = _.isArray(models) ? models.slice() : [models];

      // Begin by turning bare objects into model references, and preventing
      // invalid models or duplicate models from being added.
      for (i = 0, length = models.length; i < length; i++) {
        if (!(model = models[i] = this._prepareModel(models[i], options))) {
          throw new Error("Can't add an invalid model to a collection");
        }
        cid = model.cid;
        id = model.id;
        if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
          dups.push(i);
          continue;
        }
        cids[cid] = ids[id] = model;
      }

      // Remove duplicates.
      i = dups.length;
      while (i--) {
        models.splice(dups[i], 1);
      }

      // Listen to added models' events, and index models for lookup by
      // `id` and by `cid`.
      for (i = 0, length = models.length; i < length; i++) {
        (model = models[i]).on('all', this._onModelEvent, this);
        this._byCid[model.cid] = model;
        if (model.id != null) this._byId[model.id] = model;
      }

      // Insert models into the collection, re-sorting if needed, and triggering
      // `add` events unless silenced.
      this.length += length;
      index = options.at != null ? options.at : this.models.length;
      splice.apply(this.models, [index, 0].concat(models));
      if (this.comparator) this.sort({silent: true});
      if (options.silent) return this;
      for (i = 0, length = this.models.length; i < length; i++) {
        if (!cids[(model = this.models[i]).cid]) continue;
        options.index = i;
        model.trigger('add', model, this, options);
      }
      return this;
    },

    // Remove a model, or a list of models from the set. Pass silent to avoid
    // firing the `remove` event for every model removed.
    remove: function(models, options) {
      var i, l, index, model;
      options || (options = {});
      models = _.isArray(models) ? models.slice() : [models];
      for (i = 0, l = models.length; i < l; i++) {
        model = this.getByCid(models[i]) || this.get(models[i]);
        if (!model) continue;
        delete this._byId[model.id];
        delete this._byCid[model.cid];
        index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;
        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }
        this._removeReference(model);
      }
      return this;
    },

    // Add a model to the end of the collection.
    push: function(model, options) {
      model = this._prepareModel(model, options);
      this.add(model, options);
      return model;
    },

    // Remove a model from the end of the collection.
    pop: function(options) {
      var model = this.at(this.length - 1);
      this.remove(model, options);
      return model;
    },

    // Add a model to the beginning of the collection.
    unshift: function(model, options) {
      model = this._prepareModel(model, options);
      this.add(model, _.extend({at: 0}, options));
      return model;
    },

    // Remove a model from the beginning of the collection.
    shift: function(options) {
      var model = this.at(0);
      this.remove(model, options);
      return model;
    },

    // Get a model from the set by id.
    get: function(id) {
      if (id == null) return void 0;
      return this._byId[id.id != null ? id.id : id];
    },

    // Get a model from the set by client id.
    getByCid: function(cid) {
      return cid && this._byCid[cid.cid || cid];
    },

    // Get the model at the given index.
    at: function(index) {
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of `filter`.
    where: function(attrs) {
      if (_.isEmpty(attrs)) return [];
      return this.filter(function(model) {
        for (var key in attrs) {
          if (attrs[key] !== model.get(key)) return false;
        }
        return true;
      });
    },

    // Force the collection to re-sort itself. You don't need to call this under
    // normal circumstances, as the set will maintain sort order as each item
    // is added.
    sort: function(options) {
      options || (options = {});
      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
      var boundComparator = _.bind(this.comparator, this);
      if (this.comparator.length == 1) {
        this.models = this.sortBy(boundComparator);
      } else {
        this.models.sort(boundComparator);
      }
      if (!options.silent) this.trigger('reset', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck: function(attr) {
      return _.map(this.models, function(model){ return model.get(attr); });
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any `add` or `remove` events. Fires `reset` when finished.
    reset: function(models, options) {
      models  || (models = []);
      options || (options = {});
      for (var i = 0, l = this.models.length; i < l; i++) {
        this._removeReference(this.models[i]);
      }
      this._reset();
      this.add(models, _.extend({silent: true}, options));
      if (!options.silent) this.trigger('reset', this, options);
      return this;
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `add: true` is passed, appends the
    // models to the collection instead of resetting.
    fetch: function(options) {
      options = options ? _.clone(options) : {};
      if (options.parse === undefined) options.parse = true;
      var collection = this;
      var success = options.success;
      options.success = function(resp, status, xhr) {
        collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
        if (success) success(collection, resp);
      };
      options.error = Backbone.wrapError(options.error, collection, options);
      return (this.sync || Backbone.sync).call(this, 'read', this, options);
    },

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      var coll = this;
      options = options ? _.clone(options) : {};
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!options.wait) coll.add(model, options);
      var success = options.success;
      options.success = function(nextModel, resp, xhr) {
        if (options.wait) coll.add(nextModel, options);
        if (success) {
          success(nextModel, resp);
        } else {
          nextModel.trigger('sync', model, resp, options);
        }
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse: function(resp, xhr) {
      return resp;
    },

    // Proxy to _'s chain. Can't be proxied the same way the rest of the
    // underscore methods are proxied because it relies on the underscore
    // constructor.
    chain: function () {
      return _(this.models).chain();
    },

    // Reset all internal state. Called when the collection is reset.
    _reset: function(options) {
      this.length = 0;
      this.models = [];
      this._byId  = {};
      this._byCid = {};
    },

    // Prepare a model or hash of attributes to be added to this collection.
    _prepareModel: function(model, options) {
      options || (options = {});
      if (!(model instanceof Model)) {
        var attrs = model;
        options.collection = this;
        model = new this.model(attrs, options);
        if (!model._validate(model.attributes, options)) model = false;
      } else if (!model.collection) {
        model.collection = this;
      }
      return model;
    },

    // Internal method to remove a model's ties to a collection.
    _removeReference: function(model) {
      if (this == model.collection) {
        delete model.collection;
      }
      model.off('all', this._onModelEvent, this);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent: function(event, model, collection, options) {
      if ((event == 'add' || event == 'remove') && collection != this) return;
      if (event == 'destroy') {
        this.remove(model, options);
      }
      if (model && event === 'change:' + model.idAttribute) {
        delete this._byId[model.previous(model.idAttribute)];
        this._byId[model.id] = model;
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Underscore methods that we want to implement on the Collection.
  var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
    'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
    'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
    'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
    'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];

  // Mix in each Underscore method as a proxy to `Collection#models`.
  _.each(methods, function(method) {
    Collection.prototype[method] = function() {
      return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
    };
  });

  // Backbone.Router
  // -------------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var namedParam    = /:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[-[\]{}()+?.,\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route: function(route, name, callback) {
      Backbone.history || (Backbone.history = new History);
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (!callback) callback = this[name];
      Backbone.history.route(route, _.bind(function(fragment) {
        var args = this._extractParameters(route, fragment);
        callback && callback.apply(this, args);
        this.trigger.apply(this, ['route:' + name].concat(args));
        Backbone.history.trigger('route', this, name, args);
      }, this));
      return this;
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes: function() {
      if (!this.routes) return;
      var routes = [];
      for (var route in this.routes) {
        routes.unshift([route, this.routes[route]]);
      }
      for (var i = 0, l = routes.length; i < l; i++) {
        this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&')
                   .replace(namedParam, '([^\/]+)')
                   .replace(splatParam, '(.*?)');
      return new RegExp('^' + route + '$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted parameters.
    _extractParameters: function(route, fragment) {
      return route.exec(fragment).slice(1);
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on URL fragments. If the
  // browser does not support `onhashchange`, falls back to polling.
  var History = Backbone.History = function() {
    this.handlers = [];
    _.bindAll(this, 'checkUrl');
  };

  // Cached regex for cleaning leading hashes and slashes .
  var routeStripper = /^[#\/]/;

  // Cached regex for detecting MSIE.
  var isExplorer = /msie [\w.]+/;

  // Has the history handling already been started?
  History.started = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(History.prototype, Events, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Gets the true hash value. Cannot use location.hash directly due to bug
    // in Firefox where location.hash will always be decoded.
    getHash: function(windowOverride) {
      var loc = windowOverride ? windowOverride.location : window.location;
      var match = loc.href.match(/#(.*)$/);
      return match ? match[1] : '';
    },

    // Get the cross-browser normalized URL fragment, either from the URL,
    // the hash, or the override.
    getFragment: function(fragment, forcePushState) {
      if (fragment == null) {
        /*
         * merge from Bacbone 0.9.2
         * https://github.com/documentcloud/backbone/blob/b536b137b8f987953de4174b34af75b996889387/backbone.js
         */
        if (this._hasPushState || !this._wantsHashChange || forcePushState) {
        /*if (this._hasPushState || forcePushState) {*/
          fragment = window.location.pathname;
          // var search = window.location.search;
          // if (search) fragment += search;
        } else {
          fragment = this.getHash();
        }
      }
      if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
      return fragment.replace(routeStripper, '');
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start: function(options) {
      if (History.started) throw new Error("Backbone.history has already been started");
      History.started = true;

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      this.options          = _.extend({}, {root: '/'}, this.options, options);
      this._wantsHashChange = this.options.hashChange !== false;
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.options.pushState && window.history && window.history.pushState);
      var fragment          = this.getFragment();
      var docMode           = document.documentMode;
      var oldIE             = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));

      /*
       * merge from Bacbone 0.9.2
       * https://github.com/documentcloud/backbone/blob/b536b137b8f987953de4174b34af75b996889387/backbone.js
       */
      if (oldIE && this._wantsHashChange) {
      /*if (oldIE) {*/
        this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
        this.navigate(fragment);
      }

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._hasPushState) {
        $(window).bind('popstate', this.checkUrl);
      } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
        $(window).bind('hashchange', this.checkUrl);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      // Determine if we need to change the base url, for a pushState link
      // opened by a non-pushState browser.
      this.fragment = fragment;
      var loc = window.location;
      var atRoot  = loc.pathname == this.options.root;

      // If we've started off with a route from a `pushState`-enabled browser,
      // but we're currently in a browser that doesn't support it...
      if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
        this.fragment = this.getFragment(null, true);
        window.location.replace(this.options.root + '#' + this.fragment);
        // Return immediately as browser will do redirect to new url
        return true;

      // Or if we've started out with a hash-based route, but we're currently
      // in a browser where it could be `pushState`-based instead...
      } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
        this.fragment = this.getHash().replace(routeStripper, '');
        window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
      }

      if (!this.options.silent) {
        return this.loadUrl();
      }
    },

    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
    // but possibly useful for unit testing Routers.
    stop: function() {
      $(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
      clearInterval(this._checkUrlInterval);
      History.started = false;
    },

    // Add a route to be tested when the fragment changes. Routes added later
    // may override previous routes.
    route: function(route, callback) {
      this.handlers.unshift({route: route, callback: callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl: function(e) {
      var current = this.getFragment();
      if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
      if (current == this.fragment) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl() || this.loadUrl(this.getHash());
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl: function(fragmentOverride) {
      var fragment = this.fragment = this.getFragment(fragmentOverride);
      var matched = _.any(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
      return matched;
    },

    // Save a fragment into the hash history, or replace the URL state if the
    // 'replace' option is passed. You are responsible for properly URL-encoding
    // the fragment in advance.
    //
    // The options object can contain `trigger: true` if you wish to have the
    // route callback be fired (not usually desirable), or `replace: true`, if
    // you wish to modify the current URL without adding an entry to the history.
    navigate: function(fragment, options) {
      if (!History.started) return false;
      if (!options || options === true) options = {trigger: options};
      var frag = (fragment || '').replace(routeStripper, '');
      if (this.fragment == frag) return;

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._hasPushState) {
        if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
        this.fragment = frag;
        window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
      } else if (this._wantsHashChange) {
        this.fragment = frag;
        this._updateHash(window.location, frag, options.replace);
        if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
          // Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
          // When replace is true, we don't want this.
          if(!options.replace) this.iframe.document.open().close();
          this._updateHash(this.iframe.location, frag, options.replace);
        }

      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
      } else {
        window.location.assign(this.options.root + fragment);
      }
      if (options.trigger) this.loadUrl(fragment);
    },

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    _updateHash: function(location, fragment, replace) {
      if (replace) {
        location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
      } else {
        location.hash = fragment;
      }
    }
  });

  // Backbone.View
  // -------------

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    this._configure(options || {});
    this._ensureElement();
    this.initialize.apply(this, arguments);
    this.delegateEvents();
  };

  // Cached regex to split keys for `delegate`.
  var delegateEventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be merged as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(View.prototype, Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // jQuery delegate for element lookup, scoped to DOM elements within the
    // current view. This should be prefered to global lookups where possible.
    $: function(selector) {
      return this.$el.find(selector);
    },

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    // Remove this view from the DOM. Note that the view isn't present in the
    // DOM by default, so calling this method may be a no-op.
    remove: function() {
      this.$el.remove();
      return this;
    },

    // For small amounts of DOM Elements, where a full-blown template isn't
    // needed, use **make** to manufacture elements, one at a time.
    //
    //     var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
    //
    make: function(tagName, attributes, content) {
      var el = document.createElement(tagName);
      if (attributes) $(el).attr(attributes);
      if (content != null) $(el).html(content);
      return el;
    },

    // Change the view's element (`this.el` property), including event
    // re-delegation.
    setElement: function(element, delegate) {
      if (this.$el) this.undelegateEvents();
      this.$el = (element instanceof $) ? element : $(element);
      this.el = this.$el[0];
      if (delegate !== false) this.delegateEvents();
      return this;
    },

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save'
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    // This only works for delegate-able events: not `focus`, `blur`, and
    // not `change`, `submit`, and `reset` in Internet Explorer.
    delegateEvents: function(events) {
      if (!(events || (events = getValue(this, 'events')))) return;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[events[key]];
        if (!method) throw new Error('Method "' + events[key] + '" does not exist');
        var match = key.match(delegateEventSplitter);
        var eventName = match[1], selector = match[2];
        method = _.bind(method, this);
        eventName += '.delegateEvents' + this.cid;
        if (selector === '') {
          this.$el.bind(eventName, method);
        } else {
          this.$el.delegate(selector, eventName, method);
        }
      }
    },

    // Clears all callbacks previously bound to the view with `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
    undelegateEvents: function() {
      this.$el.unbind('.delegateEvents' + this.cid);
    },

    // Performs the initial configuration of a View with a set of options.
    // Keys with special meaning *(model, collection, id, className)*, are
    // attached directly to the view.
    _configure: function(options) {
      if (this.options) options = _.extend({}, this.options, options);
      for (var i = 0, l = viewOptions.length; i < l; i++) {
        var attr = viewOptions[i];
        if (options[attr]) this[attr] = options[attr];
      }
      this.options = options;
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this.make(this.tagName, attrs), false);
      } else {
        this.setElement(this.el, false);
      }
    }

  });

  // The self-propagating extend function that Backbone classes use.
  var extend = function (protoProps, classProps) {
    var child = inherits(this, protoProps, classProps);
    child.extend = this.extend;
    return child;
  };

  // Set up inheritance for the model, collection, and view.
  Model.extend = Collection.extend = Router.extend = View.extend = extend;

  // Backbone.sync
  // -------------

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'delete': 'DELETE',
    'read':   'GET'
  };

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    options || (options = {});

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = getValue(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (!options.data && model && (method == 'create' || method == 'update')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(model.toJSON());
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (Backbone.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (Backbone.emulateHTTP) {
      if (type === 'PUT' || type === 'DELETE') {
        if (Backbone.emulateJSON) params.data._method = type;
        params.type = 'POST';
        params.beforeSend = function(xhr) {
          xhr.setRequestHeader('X-HTTP-Method-Override', type);
        };
      }
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !Backbone.emulateJSON) {
      params.processData = false;
    }

    // Make the request, allowing the user to override any Ajax options.
    return $.ajax(_.extend(params, options));
  };

  // Wrap an optional error callback with a fallback error event.
  Backbone.wrapError = function(onError, originalModel, options) {
    return function(model, resp) {
      resp = model === originalModel ? resp : model;
      if (onError) {
        onError(originalModel, resp, options);
      } else {
        originalModel.trigger('error', originalModel, resp, options);
      }
    };
  };

  // Helpers
  // -------

  // Shared empty constructor function to aid in prototype-chain creation.
  var ctor = function(){};

  // Helper function to correctly set up the prototype chain, for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var inherits = function(parent, protoProps, staticProps) {
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent's constructor.
    if (protoProps && protoProps.hasOwnProperty('constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ parent.apply(this, arguments); };
    }

    // Inherit class (static) properties from parent.
    _.extend(child, parent);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function.
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();

    // Add prototype properties (instance properties) to the subclass,
    // if supplied.
    if (protoProps) _.extend(child.prototype, protoProps);

    // Add static properties to the constructor function, if supplied.
    if (staticProps) _.extend(child, staticProps);

    // Correctly set child's `prototype.constructor`.
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Helper function to get a value from a Backbone object as a property
  // or as a function.
  var getValue = function(object, prop) {
    if (!(object && object[prop])) return null;
    return _.isFunction(object[prop]) ? object[prop]() : object[prop];
  };

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  return Backbone;
}));

/**
 * @fileoverview Global PubSub ("event aggregator") object.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 */
define('pubsub',['underscore', 'backbone'],
    function(_, Backbone) {


        /**
         * Extend Backbone.Events to a global object used for PubSub.
         */
        var PubSub = _.extend({}, Backbone.Events);

        PubSub.attach = function(events, context) {
            _.each(events, _.bind(function(callback, eventName){
                this.on(eventName, callback, context);
            }, this));
        };

        PubSub.unattach = function(events, context) {
            _.each(events, _.bind(function(callback, eventName){
                this.off(eventName, callback, context);
            }, this));
        };

        var origTrigger = PubSub.trigger;
        PubSub.trigger = function(events){
            try{
                origTrigger.apply(PubSub, arguments);
            }catch(ex){
                console.error('PubSub trigger "' + events + '" threw exception: ',
                    (ex.stack || ex.stacktrace || ex.message));
            }
            return PubSub;
        };

        return PubSub;
    }
);

/**
 * @fileoverview Global App "model" object to be used for any globally required
 * references -- cached DOM lookups, global properties, etc.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 */
/*global Modernizr:true*/
define('app',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub'
],
function(
    $,
    _,
    Backbone,
    PubSub
){
    
    var AppModel = Backbone.Model.extend({

        initialize: function() {
            this.set('DEBUG', true);

            // Set global properties/lookups.
            this.set('document', $(document));
            this.set('win', $(window));
            this.set('body', $('body'));
            this.set('scrollEl', $('html,body'));
            this.set('doc', $(document));
            this.set('navEl', $('#nav'));
            this.set('headerEl', $('#header'));
            this.set('breakingEl', $('#breaking'));
            this.set('breakingWrapEl', $('#breaking-wrap'));
            this.baseUrl = window.location.protocol + '//' + window.location.host + '/';
            this.usatBetaDomain = 'http://beta.usatoday.com/';
        },

        /*
         * the page's url, without any query string or hashtags
         * this should always be valid (or the app is broken)
         */
        getPageUrl: function() {
            return document.location.protocol+'//'+document.location.host+document.location.pathname;
        },

        /*
         * Get element and call heattracking with it.
         * @param {jQuery selector} $sel Selector to heattrack.
         */
        setTrack: function($sel, ht, uotrack) {
            if ($sel && $sel.length) {
                ht = $sel.data('ht');
                uotrack = $sel.data('uotrack');
            }
            if (ht) PubSub.trigger('heattrack', ht);
            if (uotrack) PubSub.trigger('uotrack', uotrack);
        },

        getScrollPosition: function(){
            return window.pageYOffset || document.body.scrollTop;
        },

        /**
         * Load externally hosted script (SDK, library, etc) on-demand.
         * @param {string} scriptUrl URL of script file.
         * @param {string} symbol Unique window property from external
         *     script to validate the script has been successfully loaded.
         * @param {Function} callback Function to call when script has loaded.
         */
        loadScript: function(scriptUrl, symbol, callback) {
            if (window[symbol]) {
                callback();
            } else {
                require([scriptUrl], function(){
                    if (!window[symbol]) {
                        console.error('Error loading ' + scriptUrl);
                    } else {
                        callback();
                    }
                });
            }
        },

        /**
         * Open a centered popup window.
         * @param {string} url URL to load in the popup.
         * @param {number=} width Width of popup.
         * @param {number=} height Height of popup.
         */
        openPopup: function(url, width, height) {
            width = width || 600;
            height = height || 400;
            var winCoords = this.popupCoords(width, height);
            window.open(
                url,
                '',
                'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,' +
                'height='+ height +',width='+ width +',top='+ winCoords.top +
                ',left='+ winCoords.left
            );
        },

        /**
         * Calculate and return coordinates for centering a popup window to
         *     the outerWidth/outerHeight of the browser window.
         * @param {number} w Width of popup window.
         * @param {number} h Height of popup window.
         */
        popupCoords: function(w, h) {
            var wLeft = window.screenLeft ? window.screenLeft : window.screenX;
            var wTop = window.screenTop ? window.screenTop : window.screenY;
            var wWidth = window.outerWidth ? window.outerWidth : document.documentElement.clientWidth;
            var wHeight = window.outerHeight ? window.outerHeight : document.documentElement.clientHeight;

            // Subtract 25 pixels to top to approximately compensate for chrome
            // on top of popup window, since we can't calculate that before
            // opening it.
            return {
                left: wLeft + (wWidth / 2) - (w / 2),
                top: wTop + (wHeight / 2) - (h / 2) - 25
            };
        },

        /**
         * Check if fragment matches defined 'Router' routes.
         * NOTE: using internal Backbone.history functions -- when upgrading
         * Backbone, must ensure these functions stil exist.
         * @param {string} fragment Url fragment to test.
         */
        getDefinedRoute: function(fragment) {
            if (fragment === '#') return null;
            // strip out usatDomain
            fragment = fragment.replace(this.usatDomainRegex, '');
            if (!fragment.indexOf(this.baseUrl)){
                fragment = fragment.substring(this.baseUrl.length);
            } else if (!fragment.indexOf(this.usatBetaDomain)) {
                fragment = fragment.substring(this.usatBetaDomain.length);
            } else if (fragment.indexOf('://') !== -1){
                return null;
            }
            // this trims off the root of the fragment if one exists
            fragment = Backbone.history.getFragment(fragment);
            var matched = _.any(Backbone.history.handlers, function(handler) {
                return handler.route.test(fragment);
            });
            if (matched){
                return fragment;
            } else{
                return null;
            }
        },

        /**
         * Handle links.
         *
         */
        triggerRoute: function(targetLink, ht, uotrack){
            var href;
            if (targetLink instanceof $ || _.isElement(targetLink)) {
                var $targetLink = $(targetLink);
                href = $targetLink.attr('href');
                this.setTrack($targetLink);
            } else if (_.isString(targetLink)) {
                href = targetLink;
                this.setTrack(undefined, ht, uotrack);
            }
            href = $.trim(href);
            if (this.isValidUrl(href)){
                if (Modernizr.history){
                    var fragment = this.getDefinedRoute(href);
                    if (fragment !== null){
                        Backbone.history.navigate(fragment, {trigger: true});
                        return true;
                    }
                }
                window.location = href;
                return true;
            } else {
                return false;
            }
        },

        isValidUrl: function(href){
            if (!href){
                return false;
            } else if (href.indexOf('javascript:') !== -1){
                return false;
            } else if (href[0] === '#' && href.length === 1){
                return false;
            } else if (href.indexOf('../') !== -1){
                console.error('Attempting to load a relative url, bad code monkey! (' + href + ')');
                return false;
            } else if (href[0] !== '/' && href.indexOf('://') === -1){
                console.error('Attempting to load a relative url, bad code monkey! (' + href + ')');
                return false;
            }
            return true;
        },

        /**
         * Format number (or string version of number) to use commas.
         * 40532 -> 40,532
         *
         * @param {int} nStr Number to format
         */
        addCommas: function(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        },

        /**
         * Lazy load an image. Moves data-src attribute to src.
         * @param {jQuery} $img jQuery object e.g. $('img')
         * @param {String} [dataSrcAttr="data-src"] optional parameter to specify which dataSrcAttr to retrieve
         * @param {Boolean} [keepAttr=false] optional parameter that will keep the attribute instead of deleting it
         * @param {Function} [onError] optional function to call when an image fails to load
         * @returns {Boolean} true if a lazy image was found and triggered to load
         */
        lazyLoadImage: function($img, dataSrcAttr, keepAttr, onError) {
            var hasLazyImage = false;
            dataSrcAttr = dataSrcAttr || 'data-src';
            $img.each(_.bind(function(index, el){
                var dataSrc = $(el).attr(dataSrcAttr), src = $(el).attr('src');
                if (dataSrc && src !== dataSrc) {
                    $(el).attr('src', dataSrc);
                    if (!keepAttr){
                        $(el).removeAttr(dataSrcAttr);
                    }
                    $(el).on('error', _.bind(this.lazyLoadError, $(el), onError));
                    hasLazyImage = true;
                }
            }, this));
            return hasLazyImage;
        },

        /**
         * get section path function
         * returns the section name without the slash
         * @param {String} [path] story folder path.
         */
        getSectionPath: function(path){
            if (path && path !== '/'){
                var slashIndex = path.indexOf('/');
                if (slashIndex === -1){
                    return path;
                }else{
                    return path.substring(0, slashIndex);
                }
            }else{
                return 'home';
            }
        },

        /**
         * Lazy load error function
         * hides the image that threw the error, optionally calls an error function
         * @param {Function} [onError] optional function to call when an image fails to load.
         */
        lazyLoadError: function(onError) {
            $(this).hide();
            if (onError) {
                onError();
            }
        },

        /**
         * Given a url to require, will load once and immediately clean up
         * @return {Deferred}
         */
        requireSingleUseScript: function(script) {
            return $.Deferred(function(defer) {
                require([script], function(view) {
                    defer.resolveWith(this, [view]);
                }, function (err) {
                    console.error('failed loading scripts', err);
                    defer.rejectWith(this, err);
                });
            }).always(_.bind(function() {
                // cleanup
                this.removeRequireModule(script);
            }, this)).promise();
        },

        removeRequireModule: function(url){
            require.undef(url);
            $('script[data-requiremodule="' + url + '"]').remove();
        },

        getUrlParam : function(key) {
            var s = decodeURI((new RegExp(key + '=' + '(.+?)(&|$)').exec(window.location.search)||[0,false])[1]);
            if (s === 'false') {
                return false;
            } else if (s === 'true') {
                return true;
            }
            return s;
        },

        getSessionData: function(key, defaultValue) {
            var value;
            if (Modernizr.localstorage) {
                value = sessionStorage[key];
            }else {
                value = $.cookie(key);
            }
            return (value && $.parseJSON(value)) || defaultValue;
        },

        setSessionData: function(key, value) {
            if (!_.isString(value)) {
                value = JSON.stringify(value);
            }
            if (Modernizr.localstorage) {
                sessionStorage.setItem(key, value);
            } else {
                $.cookie(key, value);
            }
        },

        clearSessionData: function(key) {
            if (Modernizr.localstorage) {
                sessionStorage.removeItem(key);
            } else {
                $.cookie(key, null);
            }
        }
    });

    /**
     * Extend Backbone.Model to a global object.
     */
    return new AppModel();
});

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright Â© 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */;
define("easing", function(){});

/**
 * @fileoverview Global alert view. Display loading messages, prompts,
 * confirmation messages, etc.
 * @author kris.hedstrom@f-i.com (Kris Hedstrom)
 */
define('views/modules/alert',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'easing'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App
) {

    /**
     * View class.
     */
    var Alert = Backbone.View.extend({

        el: 'body',

        // Events.
        events: {},

        /**
         * Initialize the view.
         */
        initialize: function(options) {
            
            this.options = $.extend({
                templateID: 'alert'
            }, options || {});
   
            this.render();
        },

        /**
         * Create markup for alert.
         * @TODO: separate this out to a underscore template.
         */
        render: function() {
            this.$alert = $('<div class="ui-alert"><span class="text"></span><span class="close-btn">Close</span></div>')
                            .appendTo(this.$el);
            this.$alertText = this.$alert.find('.text');
            this.$alert.on('click', '.close-btn', _.bind(function(){
                this.hidePrompt();
            }, this));
        },

        /**
         * Display alert.
         * @param {String} msg The HTML to display.
         */
        show: function(msg) {
            PubSub.trigger('show:alert');
            this.$alertText.html(msg);
            this.$alert.addClass('active').removeClass('error');
        },

        /**
         * Hide the alert.
         */
        hide: function() {
            PubSub.trigger('hide:alert');
            this.$alert.removeClass('active').removeClass('error');
        },

        /**
         * Display error message.
         * @param {String} msg The HTML to display.
         */
        showError: function(msg) {
            PubSub.trigger('show:error:alert');
            this.$alertText.html(msg);
            this.$alert.addClass('active').addClass('error');
        },

        showPrompt: function(msg, confirmCallback, cancelCallback) {

            /**
             * Confirmation event handler. Stops default events and calls
             * confirmation callback.
             * @private
             */
            function _confirm(e) {
                e.preventDefault();
                e.stopPropagation();
                if(typeof confirmCallback === 'function') confirmCallback();
            }
            
            /**
             * Cancel handler. Stops default events and calls cancel callback.
             * @private
             */
            function _cancel (e) {
                e.preventDefault();
                e.stopPropagation();
                if(typeof cancelCallback === 'function') cancelCallback();
            }
            
            // @TODO: make this more flexible.
            var confirm = $('<a/>', {
                'html': 'Okay'
            });

            var cancel = $('<a/>', {
                'html': 'Cancel'
            });

            var txt = $('<div/>', {
                'class': 'prompt',
                'html': msg
            });

            txt.append(confirm).append(cancel);
            this.$alert.addClass('active').html(txt);

            confirm.on('click', _confirm);
            cancel.on('click', _cancel);

        },

        /**
         * Hide the confirmation prompt.
         */
        hidePrompt: function() {
            this.$alert.removeClass('active');
        }

    });

    /**
     * Return singleton.
     */
    return new Alert();
});

/**
 * @fileoverview Traffic Cop that will gate dom changing ajax events until animations are complete.
 * The advantage of this is that multiple animations could all be happening, and ajax requests will
 * stall until an appropriate window is available to render it's content
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('managers/trafficcop',['jquery', 'underscore'],
    function($, _) {
        var TrafficCop = function(){
            this.DEBUG = true;
            this.animationTimeout = 2000; // ms
            this.activeRequests = [];
            this.activeAnimations = [];
            this.animationCompletion = null;
        };
        TrafficCop.prototype = {
            /**
             * Adds an ajax request to the traffic manager. No ajax requests will complete (success or error)
             * until all animations have completed.
             * @param ajaxPromise {jQuery Promise Object} promise object representing an ajax request
             * @return {jQuery Promise Object} promise object that will fire when all animations are done
             */
            addRequest: function(ajaxPromise){
                var resultPromise = {
                    ajaxPromise: ajaxPromise,
                    gate: $.Deferred(),
                    requestResult: null
                };
                this.activeRequests.push(resultPromise);
                ajaxPromise.always(_.bind(function(requestResult){
                    resultPromise.requestResult = requestResult;
                    if (this.activeAnimations.length === 0){
                        if (ajaxPromise.state() === 'resolved'){
                            resultPromise.gate.resolve();
                        }else{
                            resultPromise.gate.reject();
                        }
                        this._clearFinishedRequests();
                    }
                }, this));
                // we need to filter the results, cause we're not returning the correct promise
                var gate = resultPromise.gate.promise();
                // copy the abort function pointer
                gate = gate.pipe(function(){
                    return resultPromise.requestResult;
                }, function(e){
                    return resultPromise.requestResult;
                });
                gate.abort = ajaxPromise.abort;
                return gate;
            },
            /**
             * Adds an animation to the traffic cop. No requests will complete until all animations
             * finish. The function will return a global completion promise that will fire when
             * all animations are done
             * @param deferred {jQuery Promise Object} representing an animation that will eventually complete
             * @return {jQuery Promise Object} representing when all animations are done
             */
            addAnimation: function(promise, el, property, value){
                // why are you wasting my time?
                if (!promise || promise.state() !== 'pending'){
                    return promise;
                }
                if (!this.animationCompletion){
                    this.animationCompletion = $.Deferred();
                }
                var animationInfo = {
                    promise: promise,
                    el: el && el[0],
                    property: property,
                    value: value
                };
                animationInfo.timeout = setTimeout(_.bind(function(){
                    console.warn('ANIMATION did NOT resolve within ' + this.animationTimeout + ' ms, releasing barrier ' + this._getAnimationPropertyDescription(property, value), animationInfo.el);
ANIMATION did NOT resolve within 2000 ms, releasing barrier on unregistered element undefined
                    this.activeAnimations = _.without(this.activeAnimations, animationInfo);
                    this._resolveAnimation();
                }, this), this.animationTimeout);

                this.activeAnimations.push(animationInfo);
                promise.always(_.bind(function(){
                    window.clearTimeout(animationInfo.timeout);
                    var index = $.inArray(animationInfo, this.activeAnimations);
                    if (index !== -1){
                        this.activeAnimations.splice(index, 1);
                        this._resolveAnimation();
                    }else{
                        console.warn('animation finished after being released ' + this._getAnimationPropertyDescription(property, value), animationInfo.el);
                    }
                }, this));
                return this.animationCompletion.promise();
            },
            /**
             * Gets the current animation completion promise so we can delay destructive calls between animations
             * @return {Deferred} that will resolve when it's safe to make a destructive call
             */
            getAnimationCompletion: function() {
                if (this.animationCompletion) {
                    return this.animationCompletion.promise();
                } else {
                    return $.Deferred().resolve();
                }
            },
            _getAnimationPropertyDescription: function(property, value){
                if (property){
                    return 'on property ' + property + ':' + value;
                }else{
                    return 'on unregistered element';
                }
            },
            _resolveAnimation: function(){
                if (this.activeAnimations.length === 0){
                    // we do this because the animation completion and the triggerEvents()
                    // might register another animation which we want to generate a new animation
                    // completion deferred
                    var completion = this.animationCompletion;
                    this.animationCompletion = null;

                    // trigger completion events
                    this._triggerEvents();
                    completion.resolve();
                }
            },
            _triggerEvents: function(){
                _.each(this.activeRequests, function(itm){
                    var state = itm.ajaxPromise.state();
                    if (state === 'resolved'){
                        itm.gate.resolve();
                    }else if (state === 'rejected'){
                        itm.gate.reject();
                    }
                });
                this._clearFinishedRequests();
            },
            _clearFinishedRequests: function(){
                this.activeRequests = _.reject(this.activeRequests, function(itm){
                    return itm.gate.state() !== 'pending';
                });
            }
        };
        return new TrafficCop();
    }
);
define('managers/requestmanager',['jquery', 'underscore', 'managers/trafficcop'],
    function($, _, TrafficCop) {
        var RequestManager = function(){
            this.DEBUG = true;
            this.navRequest = null;
            this.xhrList = [];
            this.intervalList = [];
        };
        RequestManager.prototype = {
            /**
             * Helper function that auto populates fetchData with the isHtml flag being true
             * @param path
             * @param options
             * @param isNavigation
             * @param isStatic
             * @return {Deferred} jQuery promise object
             */
            fetchHtml: function(path, options, isNavigation, isStatic){
                return this.fetchData(path, options, isNavigation, isStatic, true);
            },

            /**
             * repeatedly calls fetchHtml at a specified interval and passing the results to a callback
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} options ajax options
             * @param {Number} interval time in ms to repeat
             * @param {Function} callback function to call when fetchHtml succeeds
             * @param {Boolean} [isStatic] tells the ajax request whether to add the pjax headers or not
             * @return {Number} setInterval id
             */
            recurringFetchHtml: function(path, options, interval, callback, isStatic){
                return this.recurringFetchData(path, options, interval, callback, isStatic, true);
            },

            /**
             * repeatedly calls fetchData at a specified interval and passing the results to a callback
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} options ajax options
             * @param {Number} interval time in ms to repeat
             * @param {Function} callback function to call when fetchHtml succeeds
             * @param {Boolean} [isStatic] tells the ajax request whether to add the pjax headers or not
             * @param {Boolean} [isHtml] will return a quickly built jQuery dom object
             * @return {Number} setInterval id
             */
            recurringFetchData: function(path, options, interval, callback, isStatic, isHtml){
                var request = function(){
                    RequestManager.fetchData(path, options, false, isStatic, isHtml).done(function(html){
                        callback(html);
                    });
                };
                request();
                var id = setInterval(request, interval);
                this.intervalList.push(id);
                return id;
            },

            /**
             * Fetch data from server via AJAX. Takes a path to fetch and a
             * callback to parse the data and initialize views.
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} options ajax options
             * @param {Boolean} isNavigation specifies if this request is a navigation request
             *                  or a background loading request
             * @param {Boolean} isStatic tells the ajax request whether to add
             *      the pjax headers or not
             * @param {Boolean} isHtml will return a quickly built jQuery dom object
             * @return {Deferred} jQuery promise object
             */
            fetchData: function(path, options, isNavigation, isStatic, isHtml) {
                var proceed = this._initializeFetchData(path, isNavigation);
                if (!proceed){
                    var promise = $.Deferred().reject();
                    promise.abort = function(){};
                    return promise;
                }
                var extra_headers = {};

                if (isStatic) {
                    extra_headers['X-PJAX'] = "true";
                    extra_headers['X-PJAX-Container'] = "#overlay";
                }
                if (!path){
                    path = '/';
                }else if (path.indexOf('/') !== 0 && path.indexOf('http') !== 0){
                    path = '/' + path;
                }
                options = $.extend({
                    url: path,
                    data: {ajax: true},
                    beforeSend: function(xhr){
                        $.each(extra_headers, function(k, v){
                            xhr.setRequestHeader(k, v);
                        });
                    },
                    timeout: 30000
                }, options);

                var ajaxPromise = $.ajax(options);
                if (this.DEBUG){
                    ajaxPromise.fail(function(e){
                        if (e.statusText !== 'abort'){
                            console.log('fetchData Error: ', e.statusText, path);
                        }
                    });
                }
                var deferred = $.Deferred();
                // this will pair the ajaxPromise with any animations currently ongoing
                // it won't resolve/reject until there's an opening in the animation window
                ajaxPromise = TrafficCop.addRequest(ajaxPromise);
                this._registerNavDoneHandlers(ajaxPromise, deferred, isHtml);
                this._registerNavRequests(ajaxPromise, deferred, isNavigation);
                var returnPromise = deferred.promise();
                returnPromise.abort = _.bind(function(){
                    ajaxPromise.abort();
                    deferred.reject();
                }, this);
                return returnPromise;
            },
            _registerNavDoneHandlers: function(ajaxPromise, deferred, isHtml){
                ajaxPromise.done(function(h){
                    if (isHtml){
                        // this is a faster way of generating a jquery object from an html fragment
                        var frag = document.createDocumentFragment();
                        var div = document.createElement('div');
                        div.innerHTML = h;
                        frag.appendChild(div);
                        h = $(frag).children().children();
                    }
                    deferred.resolveWith(ajaxPromise, [h]);
                }).fail(function(e){
                    deferred.rejectWith(ajaxPromise, [e]);
                });
            },
            _registerNavRequests: function(ajaxPromise, deferred, isNavigation){
                if (isNavigation){
                    this.navRequest.xhr = ajaxPromise;
                    this.navRequest.deferred = deferred;
                    // only clear out the nav request when the promise is done
                    deferred.always(
                        _.bind(function() {
                            this.navRequest = null;
                        }, this)
                    );
                }else{
                    var navRequest = {
                        ajaxPromise: ajaxPromise,
                        resultDeferred: deferred
                    };
                    this.xhrList.push(navRequest);
                    ajaxPromise.always(_.bind(function(){
                        this.xhrList = _.without(this.xhrList, navRequest);
                    }, this));
                }
            },
            /**
             * This private function validates whether or not this fetch data should proceed
             * as well as setting up the internal structures necessary to track the request
             * @param {String} path The path being requested
             * @param {Boolean} isNavigation Boolean marking whether this is a nav or background request
             * @return {Boolean} true or false depending on whether the request should proceed
             * @private
             */
            _initializeFetchData: function(path, isNavigation){
                if (!isNavigation){
                    if (this.navRequest){
                        // reject any background requests when we're changing navigation
                        return false;
                    }
                }else{
                    if (this.navRequest){
                        // we have an existing nav request, what should we do?
                        if (this.navRequest.path === path){
                            // double clicking a link, reject it
                            return false;
                        }
                        console.log('aborting nav request');
                        // Kill any pending xhr requests.
                        if (this.navRequest.xhr){
                            this.navRequest.xhr.abort();
                        }
                        // aborting the xhr might have rejected the deferred already and cleared it out
                        if (this.navRequest && this.navRequest.deferred){
                            this.navRequest.deferred.reject();
                        }
                    }
                    // abort all background requests
                    _.each(this.xhrList, function(item){
                        item.ajaxPromise.abort();
                        item.resultDeferred.reject();
                    });
                    // abort all background intervals
                    _.each(this.intervalList, function(item){
                        clearInterval(item);
                    });
                    this.xhrList = [];
                    this.intervalList = [];
                    this.navRequest = {path: path};
                }
                return true;
            }
        };
        return new RequestManager();
    }
);
define('managers/routemanager',['jquery', 'underscore', 'backbone'],
    function($, _, Backbone) {

        var RouteManager = Backbone.Router.extend({
            initialize: function(options){
                this.options = $.extend(true, {
                    siteConfig: {},
                    onRouteChange: function(app, route, path){}
                }, options);
                this.urls = [];
                this.parseSiteConfig(this.options.siteConfig);
            },
            destroy: function(){
                Backbone.history.stop();
            },
            getRouteInfoForPath: function(path){
                return _.find(this.urls, function(url){
                    return url.url.test(path);
                });
            },
            parseSiteConfig: function(siteConfig){
                var numAppsLoaded = 0;
                var _this = this;
                _.each(siteConfig.apps, function(app){
                    require([app.appClass], function(AppClass){
                        app.appClass = AppClass;
                        numAppsLoaded++;
                        if (numAppsLoaded === siteConfig.apps.length){
                            // now that we have all the apps, register the routes and start the history
                            _.each(siteConfig.apps, function(app){
                                _.each(app.routes, function(route){
                                    _.each(route.urls, function(url){
                                        var regEx = new RegExp(url);
                                        // later urls are matched first to match backbone's route matcher
                                        _this.urls.unshift({url: regEx, appClass: app.appClass, app: app, route: route});
                                        _this.route(regEx, app.name, function(path){
                                            _this.options.onRouteChange(app, route, path);
                                        });
                                    });
                                });
                            });
                            Backbone.history.start({pushState: true, hashChange: false});
                            console.log("App Loaded");
                        }
                    });
                });
            }
        });
        return RouteManager;
    }
);
/**
 * @fileoverview Resource Manager that handles loading modularized javascript and css
 * For CSS, it maintains a state of what's currently loaded so it can unload files as need be.
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('managers/resourcemanager',['jquery', 'underscore'],
    function($, _) {
        
        var ResourceManager = function(){
            this._initialize();
        };
        ResourceManager.prototype = {
            /**
             * private function that sets up resource manager
             * @private
             */
            _initialize: function(){
                this.$stylesheets = $([]);
                this.stylesheets = [];
                this.staticUrl = window.site_static_url || '/static/';
                this.staticVersion = window.site_static_version || 'off';
                // build up existing stylesheets
                $('link[data-identifier]').each(_.bind(function(idx, itm) {
                    this.stylesheets.push($(itm).data('identifier'));
                    this.$stylesheets.push(itm);
                }, this));
            },
            /**
             * This function is used to add/remove stylesheets from the page
             * @param {Array} stylesheets array of stylesheets that should be on the page
             * @param {Deferred} removalPromise promise that will resolve when it's safe to remove the unneeded stylesheets
             * @param {Boolean} [log] boolean to log the changes to the stylesheets
             */
            fetchStyles: function(stylesheets, removalPromise, log){
                var newStyles = _.difference(stylesheets, this.stylesheets);
                var stylesToRemove = _.difference(this.stylesheets, stylesheets);
                if (log && stylesToRemove.length){
                    console.log('removing styles from dom: ', stylesToRemove);
                }
                if (log && newStyles.length){
                    console.log('adding styles to dom: ', newStyles);
                }
                var $stylesToRemove = this._findStyleTags(stylesToRemove);
                this.stylesheets = stylesheets;
                // _.without doesn't work on jquery objects
                this.$stylesheets = $(_.filter(this.$stylesheets, function(value){ return !_.include($stylesToRemove, value); }));
                this._addStylesToHead(newStyles);
                if ($stylesToRemove.length){
                    removalPromise.done(function(){
                        $stylesToRemove.remove();
                    });
                }
            },
            /**
             * Fetches javascript code and returns a promise that can be used to retrieve the class
             * Modules are bundled code that should contain the view
             * @param {String} [module] r.js module name that contains the view
             * @param {String} [view] name of the view class that should be returned by the promise
             * @return {Deferred} promise object
             */
            fetchJavascript: function(module, view){
                return $.Deferred(function(deferred){
                    if (module && view){
                        require([module], _.bind(function(){
                            // the view SHOULD be included in the module, if not, something went wrong
                            require([view], _.bind(function(viewClass){
                                deferred.resolveWith(this, [viewClass]);
                            }, this));
                        }, this));
                    }else if (view){
                        require([view], _.bind(function(viewClass){
                            deferred.resolveWith(this, [viewClass]);
                        }, this));
                    }else{
                        deferred.resolve();
                    }
                }).promise();
            },
            /**
             * Helper function that will return a jQuery array of the stylesheet links that match
             * the passed in array
             * @param {Array} stylesNames names of style tags we wish to find
             * @return {jQuery Array} link tags
             * @private
             */
            _findStyleTags: function(stylesNames){
                return $(_.filter(this.$stylesheets, function(itm) {
                    var section = $(itm).data('identifier');
                    return _.find(stylesNames, function(style) {
                        return section === style;
                    });
                }));
            },
            /**
             * Helper function to add new style tags to the head
             * @param {Array} newStyles names of styles we want to add
             * @private
             */
            _addStylesToHead: function(newStyles){
                if (newStyles && newStyles.length > 0) {
                    var $newStyles = $([]);
                    _.each(newStyles, function(itm) {
                        var link = $('<link rel="stylesheet" data-identifier="' + itm + '" href="' + this.staticUrl + 'css/' + itm + (window.use_minified_css ? '.min' : '') + '.css?v=' + this.staticVersion + '">')[0];
                        $newStyles.push(link);
                        this.$stylesheets.push(link);
                    }, this);
                    $('head').append($newStyles);
                }
            }
        };
        return ResourceManager;
    }
);
define('fwinfo',['jquery', 'underscore', 'backbone', 'pubsub'], function($, _, Backbone, PubSub) {
    var _cookieRECdelim = '~',
        _cookieNAMdelim = ':',
        _localcache = null;

    function _unpack_fwutil() {
        if (_localcache) {
            return;
        }
        _localcache = {};
        if (!document.cookie.match(/\bfwutil=([^\;]*)/)) {
            return;
        }
        var pairs = RegExp.$1.split(_cookieRECdelim),
            j, pair, pairs_length = pairs.length,
            pair_length;
        for (j = 0; j < pairs_length; j++) {
            pair = pairs[j].split(_cookieNAMdelim);
            pair_length = pair.length;
            if (2 == pair_length) {
                _localcache[pair[0]] = decodeURIComponent(pair[1]);
            }
        }
    }

    function _repack_fwutil() {
        var c = 'fwutil=', /* cookie string */
            d = '', /* current delimiter */
            p; /* current property name */
        for (p in _localcache) {
            if (_localcache.hasOwnProperty(p)) {
                c += d + p + _cookieNAMdelim + encodeURIComponent(_localcache[p]);
                d = _cookieRECdelim;
            }
        }
        document.cookie = c+';path=/';
    }

    var _fwInfo = new(Backbone.Model.extend({

        /*
         * interactives need an extra event on their first click
         */
        interactiveTracker: function(interactiveName) {
            this.firstClick= false;
            this.track= function(clickName) {
                if (this.firstClick == false){                        
                    PubSub.trigger('uotrack', interactiveName);
                    this.firstClick = true;
                }
                PubSub.trigger('uotrack', clickName);
            }
        },

        /*
         * dummy
         */
        getuseruniqueid: function() {
            return "";
        },

        //Retrieving  session value either from JS cache or cookie
        setsessionvalue: function(key, value) {
            if (!_localcache) {
                _unpack_fwutil();
            }
            _localcache[key] = value;
            _repack_fwutil();
        },
        getsessionvalue: function(key) {
            if (!_localcache) {
                _unpack_fwutil();
            }
            return _localcache[key];
        },
        getandclearsessionvalue: function(key) {
            var r= _fwInfo.getsessionvalue(key);
            if (!r) return null;
            _fwInfo.setsessionvalue(key, '');
            return r;
        }

    }))();

    return _fwInfo;
});

/**
 * @fileoverview State Manager that handles the application state. Maintains the active view and
 * manages routing and transitioning between the views. Ajax calls and animation calls
 * should be registered with the state manager to guarantee that animation isn't interrupted
 * and that stale or requests that are being thrown out.
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('state',[
    'jquery',
    'underscore',
    'pubsub',
    'app',
    'views/modules/alert',
    'managers/trafficcop',
    'managers/requestmanager',
    'managers/routemanager',
    'managers/resourcemanager',
    'fwinfo'
],
function(
    $,
    _,
    PubSub,
    App,
    Alert,
    TrafficCop,
    RequestManager,
    RouteManager,
    ResourceManager,
    FwInfo
) {
    
    if (!Object.getPrototypeOf) {
        // polyfill for IE8 (fullscreen transitions need it)
        Object.getPrototypeOf = function(object){
            // May break if the constructor has been tampered with
            return object.constructor.prototype;
        };
    }
        var StateManager = function(){
            this.scrollEl = App.get('scrollEl');
            this.nav = App.get('navEl');
            this.body = App.get('body');
            this.breaking = App.get('breakingEl');
            this.initialize();
            window.stateManager = this;
        };
        StateManager.prototype = {
            /** @const */
            DEBUG: true,
            /** @const */
            LAYER_OVERLAY: 'overlay',
            /** @const */
            LAYER_PRELOAD: 'preload',
            /** @const */
            LAYER_BASE: 'base',
            /** @const */
            REFRESH_FREQUENCY: 1000 * 60 * 15,

            /**
             * This starts state manager, spin up the route manager, resource manager, and refresh timer
             * @param {Object} siteConfig object representing all the apps, routes, and dependencies of the system
             */
            start: function(siteConfig) {
                this.routeManager = new RouteManager({
                    siteConfig: siteConfig,
                    onRouteChange: _.bind(this._onRouteChange, this)
                });

                this.resourceManager = new ResourceManager();

                // If click is not registered for 15 min, refresh the page --
                // for non-overlays.
                this.startRefreshTimer();
            },
            /**
             * Internal initialization helper, builds activeAppInfo and preloadedAppInfo objects
             */
            initialize: function() {
                this.activeAppInfo = {
                    path: null,
                    css: [],
                    layer: null,
                    app: null
                };
                this._clearPreloadedAppInfo();
                this.fullscreenView = null;
            },
            _clearPreloadedAppInfo: function() {
                this.preloadedAppInfo = {
                    path: null,
                    css: [],
                    app: null
                };
            },

            /**
             * Route Change callback for route manager, will make certain the correct app, route, and path
             * are loaded properly into state manager
             * @param {Object} app object representing the app that owns the path, including what class needs to be initialized
             * @param {Object} route object representing the specific route requested including what css and javascript is needed
             * @param {String} path that is being loaded
             * @private
             */
            _onRouteChange: function(app, route, path) {
                console.log('Route: ' + app.name);
                this._loadApp(app.appClass, {preloadedUrl: route.preloadedUrl || route.preloadedUrl}, path, app.overlay, route);
            },

            /**
             * Will load the given path into a preloaded/stashed state that can be quickly navigated to when asked
             * can only be used if the active app is an overlay
             * @param {String} path to preload
             * @return {Deferred} promise object that resolves when the path is fully loaded
             */
            preloadPath: function(path) {
                if (!window.chromeless && (!this.activeAppInfo.layer || this.activeAppInfo.layer === this.LAYER_OVERLAY)) {
                    return this._loadPath(path, true);
                } else {
                    return $.Deferred().reject();
                }
            },

            /**
             * Given a path, determine it's layer, resources, and how to transition to it correctly
             * @param {String} path to navigate to
             * @param {Boolean} [preload] whether this path is an active path or a preloaded path
             * @return {Deferred} promise object
             * @private
             */
            _loadPath: function(path, preload) {
                var routeInfo = this.routeManager.getRouteInfoForPath(path);
                if (!routeInfo) {
                    console.error('StateManager: tried navigating to path, but no match found: ' + path);
                    return null;
                } else if (preload) {
                    return this._preloadApp(routeInfo.appClass, {}, path, routeInfo.route);
                } else {
                    return this._loadApp(routeInfo.appClass, {}, path, routeInfo.app.overlay, routeInfo.route);
                }
            },

            navigateToPreloadedUrl: function(defaultPath) {
                var navPath = this.preloadedAppInfo.path || defaultPath || App.get('currentCardPath');
                if (!navPath) {
                    navPath = '/';
                } else if (navPath[0] !== '/') {
                    navPath = '/' + navPath;
                }
                App.triggerRoute(navPath);
            },

            /**
             * Registers a full screen view with the state manager. This is necessary because
             * the full screen view doesn't have a unique url and lives outside the knowledge
             * of the state manager
             * @param {Object} fullscreenView
             */
            registerFullScreenView: function(fullscreenView) {
                this._setFixedPosition(this.activeAppInfo.app, true);
                this.fullscreenView = fullscreenView;
                // pause the app, and all it's modules
                this.activeAppInfo.app.pause();
            },

            setActiveAppFixed: function() {
                this._setFixedPosition(this.activeAppInfo.app);
            },

            /**
             * Clears out the full screen view from the state manager
             */
            clearFullScreenView: function() {
                this._clearFixedPosition(this.activeAppInfo.app);
                // fullscreenView will be null if state manager triggered the close, which means
                // the user triggered a transition somewhere else, so don't rebuild the current view
                if (this.fullscreenView) {
                    this.fullscreenView = null;
                    // trigger a transition in place, with no requestPromise to fire beforePageReveal and afterPageReveal
                    // and restore all javascript
                    return this._loadPath(this.activeAppInfo.path);
                }
            },

            clearActiveAppFixed: function() {
                this._clearFixedPosition(this.activeAppInfo.app);
            },


            /**
             * This is the main state manager call, this will compare what the current state
             * of the universe is, and make any ajax calls, and transition to the current state
             * with the correct view information
             *
             * @param {Class} NextAppClass the javascript class that is taking over the site.
             * @param {Object} initOptions any initialization options for the view class.
             * @param {String} toPath path being loaded.
             * @param {Boolean} overlay overlay the view on top of the existing view.
             * @param {Object} routeInfo route info for the path
             */
            _loadApp: function(NextAppClass, initOptions, toPath, overlay, routeInfo) {
                var finishPromise, type = (overlay ? this.LAYER_OVERLAY : this.LAYER_BASE),
                    resourcePromise = this.resourceManager.fetchJavascript(routeInfo.module, routeInfo.view);

                this._closeFullscreenView();

                if (!this.activeAppInfo.app) {
                    // initial page load, html is already loaded, just reveal the app
                    finishPromise = this._buildNewApp(NextAppClass, initOptions, type).revealApp(null, toPath, null, resourcePromise);
                } else {
                    finishPromise = this._handleTransition(this.activeAppInfo.app, NextAppClass, initOptions,
                                                           type, this.activeAppInfo.path, toPath, resourcePromise);
                }
                this.activeAppInfo.path = toPath;
                this.activeAppInfo.css = routeInfo.css || [];
                this.resourceManager.fetchStyles(_.union(this.preloadedAppInfo.css, this.activeAppInfo.css), finishPromise);
                return finishPromise;
            },
            _preloadApp: function(NextAppClass, initOptions, toPath, routeInfo) {
                if (this.DEBUG) {
                    console.log('Router: Preloading: ', toPath);
                }
                var finishPromise = this._handleTransition(this.preloadedAppInfo.app, NextAppClass, initOptions,
                                                           this.LAYER_PRELOAD, this.preloadedAppInfo.path, toPath, $.Deferred().resolve());
                this.preloadedAppInfo.css = routeInfo.css || [];
                this.preloadedAppInfo.path = toPath;
                this.resourceManager.fetchStyles(_.union(this.preloadedAppInfo.css, this.activeAppInfo.css), finishPromise);
                return finishPromise;
            },
            _closeFullscreenView: function(){
                // full screen views live outside of the state manager because they don't
                // modify the url. If that assumption ever changes, we should switch
                // full screen view to being state managed and this hack can go away
                if (this.fullscreenView) {
                    // we need to clear out fullscreenView before calling close,
                    // because we are navigating to a new view, and don't want an accidental
                    // call to clearFullscreenView to reinstantiate the activeView
                    var fullscreenView = this.fullscreenView;
                    this.fullscreenView = null;
                    fullscreenView.close();
                }
            },
            _handleTransition: function(activeApp, NextAppClass, initOptions, requestedLayerType, fromPath, toPath, resourcePromise) {
                // the goal of this function is to trigger both an animation and an ajax request
                // at the same time. We use registerAnimation to make certain both events
                // finish at the same time before proceeding to the final phase
                var animationPromise, requestPromise, requestedApp,
                    preload = requestedLayerType === this.LAYER_PRELOAD,
                    removalPromise = this._removeCurrentApp(NextAppClass, requestedLayerType, fromPath, toPath);

                if (!removalPromise) {
                    // we're not removing the current app for a couple of reasons,
                    // 1: it's an internal transition
                    // 2: it's an overlay on top of the current app (stashing current view)

                    // fetch new html?
                    if (fromPath !== toPath) {
                        requestPromise = this._fetchPathHtml(toPath, preload);
                    }
                    if (requestedLayerType === this.LAYER_OVERLAY && this.activeAppInfo.layer === this.LAYER_BASE) {
                        requestedApp = this._buildNewApp(NextAppClass, initOptions, requestedLayerType);
                        animationPromise = this._revealOverlay(requestedApp, fromPath, toPath, requestPromise, resourcePromise);
                    } else if (preload && !this.preloadedAppInfo.app) {
                        requestedApp = this._buildNewApp(NextAppClass, initOptions, requestedLayerType);
                        animationPromise = requestedApp.revealApp(fromPath, toPath, requestPromise, resourcePromise, true);
                    } else {
                        // if we're not removing the view, let the app transition internally
                        animationPromise = activeApp.changePage(fromPath, toPath, requestPromise, resourcePromise, preload);
                    }
                } else if (requestedLayerType === this.LAYER_BASE && this.preloadedAppInfo.app) {
                    // We're requesting a base layer, and preloadedApp exists, which means removeCurrentApp
                    // didn't destroy it, so it's safe to assume it's the new app.
                    activeApp = this._movePreloadAppToActiveApp(requestedLayerType);
                    fromPath = this.activeAppInfo.path;
                    if (fromPath !== toPath) {
                        requestPromise = this._fetchPathHtml(toPath, preload);
                    }
                    animationPromise = $.Deferred(_.bind(function(defer) {
                        removalPromise.done(_.bind(function() {
                            // transition the active app to optionally trigger an animation and init it
                            activeApp.changePage(fromPath, toPath, requestPromise, resourcePromise, preload).done(function() {
                                defer.resolve();
                            });
                        }, this));
                    }, this)).promise();
                } else {
                    // We need a new app, build that bitch
                    requestPromise = this._fetchPathHtml(toPath, preload);
                    requestedApp = this._buildNewApp(NextAppClass, initOptions, requestedLayerType);
                    animationPromise = $.Deferred(_.bind(function(defer) {
                        removalPromise.done(_.bind(function() {
                            this.scrollEl.scrollTop(0);
                            requestedApp.revealApp(fromPath, toPath, requestPromise, resourcePromise, preload).done(function() {
                                defer.resolve();
                            });
                        }, this));
                    }, this)).promise();
                }
                return animationPromise;
            },
            _movePreloadAppToActiveApp: function(requestedLayer) {
                var activeApp = this.activeAppInfo.app = this.preloadedAppInfo.app;
                this.activeAppInfo.css = this.preloadedAppInfo.css;
                this.activeAppInfo.path = this.preloadedAppInfo.path;
                this.activeAppInfo.layer = requestedLayer;
                this._clearPreloadedAppInfo();
                return activeApp;
            },
            _buildNewApp: function(NewAppType, initOptions, layerType) {
                var nextView = new NewAppType(initOptions);

                // save the variables
                if (layerType === this.LAYER_PRELOAD) {
                    this.preloadedAppInfo.app = nextView;
                } else {
                    if (layerType === this.LAYER_OVERLAY && this.activeAppInfo.app && this.activeAppInfo.layer !== this.LAYER_OVERLAY) {
                        this.activeAppInfo.app.pause();
                        this.preloadedAppInfo.app = this.activeAppInfo.app;
                        this.preloadedAppInfo.path = this.activeAppInfo.path;
                        this.preloadedAppInfo.css = this.activeAppInfo.css || [];
                    }
                    this.activeAppInfo.app = nextView;
                    this.activeAppInfo.layer = layerType;
                }
                return nextView;
            },
            _revealOverlay: function(nextApp, fromPath, toPath, requestPromise, resourcePromise) {
                // save the transitionView, cause the world might change by the time we finish animating
                var transitionView = this.preloadedAppInfo.app;
                this.body.css('overflow-y', 'scroll');
                this._transitionToOverlayScroll(transitionView);
                var promise = nextApp.revealApp(fromPath, toPath, requestPromise, resourcePromise, false);
                promise.done(_.bind(function() {
                    this.body.css('overflow-y', '');
                    transitionView.afterOverlayReveal(this.scrollTop);
                }, this));
                return promise;
            },
            _removeCurrentApp: function(NewAppType, requestedLayerType, fromPath, toPath) {
                var removalPromise = null, preloadedApp = this.preloadedAppInfo.app;
                // switching from a base app to a base app, or an overlay to another overlay
                if (this.activeAppInfo.layer === requestedLayerType) {
                    if (this._shouldRemoveApp(this.activeAppInfo.app, NewAppType)) {
                        removalPromise = this.activeAppInfo.app.removeApp(fromPath, toPath);
                    }
                } else if (requestedLayerType === this.LAYER_PRELOAD) {
                    // switching from a preloaded view to another preloaded view
                    if (preloadedApp && this._shouldRemoveApp(preloadedApp, NewAppType)) {
                        removalPromise = preloadedApp.removeApp(fromPath, toPath);
                    }
                } else if (requestedLayerType === this.LAYER_BASE) {
                    // we're changing layers from overlay to base, where there might be an app that needs to be destroyed
                    if (preloadedApp) {
                        preloadedApp.beforeOverlayRemove(toPath);
                    }
                    // we always close overlays when going to normal, so no need to check anything
                    removalPromise = this.activeAppInfo.app.removeApp(fromPath, toPath);
                    if (preloadedApp) {
                        // so there's a preloaded app, do we need to remove it also?
                        if (this._shouldRemoveApp(preloadedApp, NewAppType)){
                            removalPromise = $.when(removalPromise, preloadedApp.removeApp(fromPath, toPath));
                            this._clearPreloadedAppInfo();
                        }else{
                            // otherwise, we need to transition the preloaded app from an overlay scroll
                            removalPromise.done(_.bind(function() {
                                this._transitionFromOverlayScroll(preloadedApp);
                            }, this));
                        }
                    }
                } else if (requestedLayerType === this.LAYER_OVERLAY && !this.activeAppInfo.app.isRevealed()) {
                    // opening an overlay on top of an active view, but the active view wasn't ready
                    removalPromise = this.activeAppInfo.app.removeApp(fromPath, toPath);
                }
                return removalPromise;
            },
            _shouldRemoveApp: function(currentApp, NewAppType) {
                return Object.getPrototypeOf(currentApp) !== NewAppType.prototype || !currentApp.isRevealed();
            },
            _fetchPathHtml: function(toPath, preload) {
                var requestPromise = this.fetchHtml(toPath, null, !preload);
                if (!preload) {
                    requestPromise.fail(_.bind(function(e) {
                        if (e) {
                            var msg = this.generateRequestError(e);
                            if (msg) {
                                Alert.showError(msg);
                            }
                            if ((e.status !== 200 && e.status) || e.statusText === 'timeout') {
                                // if the status is 200, means the request succeeded, but the promise was rejected/aborted
                                // status of 0 means the connection itself was aborted
                                window.history.back();
                            }
                        }
                    }, this));
                }
                return requestPromise;
            },
            generateRequestError: function(e) {
                if (e) {
                    if (e.status === 500) {
                        return 'Connection Error... (INTERNAL SERVER ERROR)';
                    } else if (e.status === 404) {
                        return 'Connection Error... (FILE NOT FOUND)';
                    } else if (e.status !== 200 && e.status) {
                        // if the status is 200, we just got canceled, otherwise we show some error message
                        return 'Connection Error... (' + (e.statusText || 'Unknown Error') + ')';
                    }
                }
                return null;
            },
            _transitionFromOverlayScroll: function(activeApp) {
                if (activeApp) {
                    if (activeApp.isApple) {
                        // fixed position and scrolltop don't get along
                        activeApp.show();
                    } else {
                        this._clearFixedPosition(activeApp);
                    }
                    // reset z-index
                    activeApp.$el.css('z-index', '');
                }
            },
            _transitionToOverlayScroll: function(activeApp) {
                if (activeApp) {
                    if (activeApp.isApple) {
                        // fixed position and scrolltop don't get along
                        activeApp.hide();
                    } else {
                        this._setFixedPosition(activeApp);
                    }
                    // force the active app to sit below the overlay
                    activeApp.$el.css('z-index', '0');
                }
            },
            _clearFixedPosition: function(activeApp) {
                var navBreakingOffset = this.getBreakingNewsOffset();
                activeApp.clearFixedPosition();
                this.scrollEl.scrollTop(Math.abs(this.scrollTop - navBreakingOffset));
            },
            _setFixedPosition: function(activeApp, partialCover) {
                this.scrollTop = this.getBreakingNewsOffset() - App.getScrollPosition();
                activeApp.setFixedPosition(this.scrollTop, partialCover);
                this.scrollEl.scrollTop(0);
            },

            /**
             * Store the timestamp of the latest activity (ie. mousemove). Used
             * to determine whether to refresh browser automatically after a
             * certain period of idle time.
             */
            updateActivityTimestamp: function() {
                this.lastActivityTimestamp = (new Date()).getTime();
            },

            getCurrentPageInfo: function(){
                return this.activeAppInfo.app.pageInfo;
            },
            getPreloadedPageInfo: function(){
                return this.preloadedAppInfo.app && this.preloadedAppInfo.app.pageInfo;
            },
            getActiveApp: function(){
                return this.activeAppInfo.app;
            },
            getPreloadedApp: function(){
                return this.preloadedAppInfo.app;
            },

            /**
             * Start refresh interval. Check current time against last activity
             * and refresh the page if it's been longer than threshold of idle
             * time.
             */
            startRefreshTimer: function() {
                if (!this.refreshTimer) {
                    this.lastActivityTimestamp = 0;
                    this.refreshTimer = setInterval(_.bind(function(){
                        if (!this.fullscreenView && this.activeAppInfo.layer !== this.LAYER_OVERLAY) {
                            var currentTime = (new Date()).getTime();
                            var idleTime = currentTime - this.lastActivityTimestamp;
                            if (idleTime > this.REFRESH_FREQUENCY) {
                                FwInfo.setsessionvalue('refreshed','refresh:'+((this.getCurrentPageInfo()||{}).ssts||'').replace(/[\/:].*/, ''));
                                window.location = window.location;
                            }
                        }
                    }, this), this.REFRESH_FREQUENCY);
                }
            },

            /**
             * Stop refresh timer.
             */
            stopRefreshTimer: function() {
                if (this.refreshTimer) {
                    clearInterval(this.refreshTimer);
                    this.refreshTimer = null;
                }
            },

            /**
             * Returns offset from nav and breaking news combined.
             */
            getBreakingNewsOffset: function() {
                return this.nav.outerHeight() + this.breaking.outerHeight();
            },

            /**
             * Registers a navigation animation that should defer all incoming ajax requests
             * @param {Deferred} deferred jQuery promise object
             * @param {jQuery} el dom element
             * @param {String} property name
             * @param {String|Number} value being animated to
             */
            registerAnimation: function(deferred, el, property, value) {
                return TrafficCop.addAnimation(deferred, el, property, value);
            },

            /**
             * Helper function that auto populates fetchData with the isHtml flag being true
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} [options] jQuery ajax option.
             * @param {Boolean} [isNavigation] specifies if this request is a navigation request
             *                  or a background loading request.
             * @param {Boolean} [isStatic] tells the ajax request whether to add
             *      the pjax headers or not
             * @return {Deferred} jQuery promise object
             */
            fetchHtml: function(path, options, isNavigation, isStatic) {
                return RequestManager.fetchHtml(path, options, isNavigation, isStatic, true);
            },

            /**
             * Fetch data from server via AJAX. Takes a path to fetch and a
             * callback to parse the data and initialize views.
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} [options] jQuery ajax option.
             * @param {Boolean} [isNavigation] specifies if this request is a navigation request
             *                  or a background loading request.
             * @param {Boolean} [isStatic] tells the ajax request whether to add
             *      the pjax headers or not
             * @param {Boolean} [isHtml] will return a quickly built jQuery dom object.
             * @return {Deferred} jQuery promise object
             */
            fetchData: function(path, options, isNavigation, isStatic, isHtml) {
                return RequestManager.fetchData(path, options, isNavigation, isStatic, isHtml);
            },

            /**
             * repeatedly calls fetchHtml at a specified interval and passing the results to a callback
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} options ajax options
             * @param {Number} interval time in ms to repeat
             * @param {Function} callback function to call when fetchHtml succeeds
             * @param {Boolean} [isStatic] tells the ajax request whether to add the pjax headers or not
             * @return {Number} setInterval id
             */
            recurringFetchHtml: function(path, options, interval, callback, isStatic){
                return RequestManager.recurringFetchHtml(path, options, isStatic, true);
            },

            /**
             * repeatedly calls fetchData at a specified interval and passing the results to a callback
             * @param {String} path The path to the ajax endpoint.
             * @param {Object} options ajax options
             * @param {Number} interval time in ms to repeat
             * @param {Function} callback function to call when fetchHtml succeeds
             * @param {Boolean} [isStatic] tells the ajax request whether to add the pjax headers or not
             * @param {Boolean} [isHtml] will return a quickly built jQuery dom object
             * @return {Number} setInterval id
             */
            recurringFetchData: function(path, options, interval, callback, isStatic, isHtml){
                return RequestManager.recurringFetchData(path, options, isStatic, isHtml);
            }
        };

        /**
         * return singleton
         */
        return new StateManager();
    });

/**
 * @license RequireJS text 2.0.3 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/requirejs/text for details
 */
/*jslint regexp: true */
/*global require: false, XMLHttpRequest: false, ActiveXObject: false,
 define: false, window: false, process: false, Packages: false,
 java: false, location: false */

define('text',['module'], function (module) {
    

    var text, fs,
        progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
        xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
        bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
        hasLocation = typeof location !== 'undefined' && location.href,
        defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
        defaultHostName = hasLocation && location.hostname,
        defaultPort = hasLocation && (location.port || undefined),
        buildMap = [],
        masterConfig = (module.config && module.config()) || {};

    text = {
        version: '2.0.3',

        strip: function (content) {
            //Strips <?xml ...?> declarations so that external SVG and XML
            //documents can be added to a document without worry. Also, if the string
            //is an HTML document, only the part inside the body tag is returned.
            if (content) {
                content = content.replace(xmlRegExp, "");
                var matches = content.match(bodyRegExp);
                if (matches) {
                    content = matches[1];
                }
            } else {
                content = "";
            }
            return content;
        },

        jsEscape: function (content) {
            return content.replace(/(['\\])/g, '\\$1')
                .replace(/[\f]/g, "\\f")
                .replace(/[\b]/g, "\\b")
                .replace(/[\n]/g, "\\n")
                .replace(/[\t]/g, "\\t")
                .replace(/[\r]/g, "\\r")
                .replace(/[\u2028]/g, "\\u2028")
                .replace(/[\u2029]/g, "\\u2029");
        },

        createXhr: masterConfig.createXhr || function () {
            //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
            var xhr, i, progId;
            if (typeof XMLHttpRequest !== "undefined") {
                return new XMLHttpRequest();
            } else if (typeof ActiveXObject !== "undefined") {
                for (i = 0; i < 3; i += 1) {
                    progId = progIds[i];
                    try {
                        xhr = new ActiveXObject(progId);
                    } catch (e) {}

                    if (xhr) {
                        progIds = [progId];  // so faster next time
                        break;
                    }
                }
            }

            return xhr;
        },

        /**
         * Parses a resource name into its component parts. Resource names
         * look like: module/name.ext!strip, where the !strip part is
         * optional.
         * @param {String} name the resource name
         * @returns {Object} with properties "moduleName", "ext" and "strip"
         * where strip is a boolean.
         */
        parseName: function (name) {
            var strip = false, index = name.indexOf("."),
                modName = name.substring(0, index),
                ext = name.substring(index + 1, name.length);

            index = ext.indexOf("!");
            if (index !== -1) {
                //Pull off the strip arg.
                strip = ext.substring(index + 1, ext.length);
                strip = strip === "strip";
                ext = ext.substring(0, index);
            }

            return {
                moduleName: modName,
                ext: ext,
                strip: strip
            };
        },

        xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,

        /**
         * Is an URL on another domain. Only works for browser use, returns
         * false in non-browser environments. Only used to know if an
         * optimized .js version of a text resource should be loaded
         * instead.
         * @param {String} url
         * @returns Boolean
         */
        useXhr: function (url, protocol, hostname, port) {
            var uProtocol, uHostName, uPort,
                match = text.xdRegExp.exec(url);
            if (!match) {
                return true;
            }
            uProtocol = match[2];
            uHostName = match[3];

            uHostName = uHostName.split(':');
            uPort = uHostName[1];
            uHostName = uHostName[0];

            return (!uProtocol || uProtocol === protocol) &&
                (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
                ((!uPort && !uHostName) || uPort === port);
        },

        finishLoad: function (name, strip, content, onLoad) {
            content = strip ? text.strip(content) : content;
            if (masterConfig.isBuild) {
                buildMap[name] = content;
            }
            onLoad(content);
        },

        load: function (name, req, onLoad, config) {
            //Name has format: some.module.filext!strip
            //The strip part is optional.
            //if strip is present, then that means only get the string contents
            //inside a body tag in an HTML string. For XML/SVG content it means
            //removing the <?xml ...?> declarations so the content can be inserted
            //into the current doc without problems.

            // Do not bother with the work if a build and text will
            // not be inlined.
            if (config.isBuild && !config.inlineText) {
                onLoad();
                return;
            }

            masterConfig.isBuild = config.isBuild;

            var parsed = text.parseName(name),
                nonStripName = parsed.moduleName + '.' + parsed.ext,
                url = req.toUrl(nonStripName),
                useXhr = (masterConfig.useXhr) ||
                    text.useXhr;

            //Load the text. Use XHR if possible and in a browser.
            if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
                text.get(url, function (content) {
                    text.finishLoad(name, parsed.strip, content, onLoad);
                }, function (err) {
                    if (onLoad.error) {
                        onLoad.error(err);
                    }
                });
            } else {
                //Need to fetch the resource across domains. Assume
                //the resource has been optimized into a JS module. Fetch
                //by the module name + extension, but do not include the
                //!strip part to avoid file system issues.
                req([nonStripName], function (content) {
                    text.finishLoad(parsed.moduleName + '.' + parsed.ext,
                        parsed.strip, content, onLoad);
                });
            }
        },

        write: function (pluginName, moduleName, write, config) {
            if (buildMap.hasOwnProperty(moduleName)) {
                var content = text.jsEscape(buildMap[moduleName]);
                write.asModule(pluginName + "!" + moduleName,
                    "define(function () { return '" +
                        content +
                        "';});\n");
            }
        },

        writeFile: function (pluginName, moduleName, req, write, config) {
            var parsed = text.parseName(moduleName),
                nonStripName = parsed.moduleName + '.' + parsed.ext,
            //Use a '.js' file name so that it indicates it is a
            //script that can be loaded across domains.
                fileName = req.toUrl(parsed.moduleName + '.' +
                    parsed.ext) + '.js';

            //Leverage own load() method to load plugin value, but only
            //write out values that do not have the strip argument,
            //to avoid any potential issues with ! in file names.
            text.load(nonStripName, req, function (value) {
                //Use own write() method to construct full module value.
                //But need to create shell that translates writeFile's
                //write() to the right interface.
                var textWrite = function (contents) {
                    return write(fileName, contents);
                };
                textWrite.asModule = function (moduleName, contents) {
                    return write.asModule(moduleName, fileName, contents);
                };

                text.write(pluginName, nonStripName, textWrite, config);
            }, config);
        }
    };

    if (masterConfig.env === 'node' || (!masterConfig.env &&
        typeof process !== "undefined" &&
        process.versions &&
        !!process.versions.node)) {
        //Using special require.nodeRequire, something added by r.js.
        fs = require.nodeRequire('fs');

        text.get = function (url, callback) {
            var file = fs.readFileSync(url, 'utf8');
            //Remove BOM (Byte Mark Order) from utf8 files if it is there.
            if (file.indexOf('\uFEFF') === 0) {
                file = file.substring(1);
            }
            callback(file);
        };
    } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
        text.createXhr())) {
        text.get = function (url, callback, errback) {
            var xhr = text.createXhr();
            xhr.open('GET', url, true);

            //Allow overrides specified in config
            if (masterConfig.onXhr) {
                masterConfig.onXhr(xhr, url);
            }

            xhr.onreadystatechange = function (evt) {
                var status, err;
                //Do not explicitly handle errors, those should be
                //visible via console output in the browser.
                if (xhr.readyState === 4) {
                    status = xhr.status;
                    if (status > 399 && status < 600) {
                        //An http 4xx or 5xx error. Signal an error.
                        err = new Error(url + ' HTTP status: ' + status);
                        err.xhr = xhr;
                        errback(err);
                    } else {
                        callback(xhr.responseText);
                    }
                }
            };
            xhr.send(null);
        };
    } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
        typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
        //Why Java, why is this so awkward?
        text.get = function (url, callback) {
            var stringBuffer, line,
                encoding = "utf-8",
                file = new java.io.File(url),
                lineSeparator = java.lang.System.getProperty("line.separator"),
                input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
                content = '';
            try {
                stringBuffer = new java.lang.StringBuffer();
                line = input.readLine();

                // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
                // http://www.unicode.org/faq/utf_bom.html

                // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
                // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
                if (line && line.length() && line.charAt(0) === 0xfeff) {
                    // Eat the BOM, since we've already found the encoding on this file,
                    // and we plan to concatenating this buffer with others; the BOM should
                    // only appear at the top of a file.
                    line = line.substring(1);
                }

                stringBuffer.append(line);

                while ((line = input.readLine()) !== null) {
                    stringBuffer.append(lineSeparator);
                    stringBuffer.append(line);
                }
                //Make sure we return a JavaScript string and not a Java string.
                content = String(stringBuffer.toString()); //String
            } finally {
                input.close();
            }
            callback(content);
        };
    }

    return text;
});
define('text!siteconfig.json',[],function () { return '{\n    "apps": [\n        {\n            "name": "Error",\n            "appClass": "views/pages/404",\n            "overlay": true,\n            "routes": [\n                {\n                    "name": "CatchAll",\n                    "urls": ["^(.*)$", "^(errors/.*)$", "^(404.html)$"]\n                }\n            ]\n        },\n        {\n            "name": "Cards",\n            "appClass": "views/modules/cards2",\n            "routes": [\n                {\n                    "name": "Generic Section",\n                    "view": "views/pages/generic-section",\n                    "mainInclude": true,\n                    "urls": ["^((news|life|tech|travel|opinion)/[a-zA-Z0-9%\\\\-/\\\\.]*)$"]\n                },\n                {\n                    "name": "Money",\n                    "view": "views/pages/money",\n                    "css": ["money"],\n                    "mainInclude": true,\n                    "urls": ["^(money/[a-zA-Z0-9%\\\\-/\\\\.]*)$"]\n                },\n                {\n                    "name": "Home",\n                    "view": "views/pages/home",\n                    "mainInclude": true,\n                    "urls": ["^()$", "^(index.html)$"]\n                },\n                {\n                    "name": "Sports",\n                    "module": "modules/sports",\n                    "view": "views/pages/sports",\n                    "css": ["sports", "sports-logos"],\n                    "urls": ["^(sports/[a-zA-Z0-9%\\\\-/\\\\.\\\\#]*)$"]\n                },\n                {\n                    "name": "Weather",\n                    "module": "modules/weather",\n                    "view": "views/pages/weather",\n                    "css": ["weather"],\n                    "urls": ["^(weather/[a-zA-Z0-9%\\\\-/\\\\.]*)$"]\n                }\n            ]\n        },\n        {\n            "name": "BigPage",\n            "appClass": "views/modules/coverview",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(big-page/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "Search",\n            "appClass": "views/pages/search",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(search/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "Topics",\n            "appClass": "views/pages/topic",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": [\n                        "^(topic/.*)$",\n                        "^(election-2012/.*)$"\n                    ]\n                }\n            ]\n        },\n        {\n            "name": "MediaView",\n            "appClass": "views/pages/media",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(media/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "Blog",\n            "appClass": "views/pages/blog",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(blog/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "UserAuth",\n            "appClass": "views/pages/userauth",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(userauth/default/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "ContactUs",\n            "appClass": "views/pages/contactus-overlay",\n            "overlay": true,\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(contactus/?)$"]\n                }\n            ]\n        },\n        {\n            "name": "SiteMap",\n            "appClass": "views/pages/sitemap",\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(sitemap/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "StaticOverlay",\n            "appClass": "views/pages/static-overlay",\n            "overlay": true,\n            "routes": [\n                {\n                    "name": "Default",\n                    "urls": ["^(shop.*|about.*|rss.*|mobile-apps.*|mediakit.*|reporters.*|legal.*|editorial-policy.*|conversation-guidelines.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "SimpleOverlay",\n            "appClass": "simpleoverlay",\n            "overlay": true,\n            "routes": [\n                {\n                    "name": "Sports BoxScores",\n                    "view": "views/pages/boxscore",\n                    "preloadedUrl": "sports/",\n                    "css": ["sports", "sports-logos"],\n                    "urls": [\n                        "^(sports/[a-zA-Z]+/game/.*)$"\n                    ]\n                },\n                {\n                    "name": "Flight Tracker",\n                    "view": "views/pages/travel/flight-tracker-overlay",\n                    "preloadedUrl": "travel/",\n                    "urls": [\n                        "^(travel/flight-tracker/.*)$"\n                    ]\n                },\n                {\n                    "name": "Final Four Bracket",\n                    "view": "views/pages/finalfourbracket",\n                    "preloadedUrl": "sports/",\n                    "urls": [\n                        "^(sports/[a-zA-Z]+/bracket/.*)$"\n                    ]\n                }\n            ]\n        },\n        {\n            "name": "Overlay",\n            "appClass": "views/modules/overlay",\n            "overlay": true,\n            "routes": [\n                {\n                    "name": "Story",\n                    "module": "modules/story",\n                    "view": "views/pages/story",\n                    "urls": [\n                        "^((photos|interactives|picture-gallery|videos|story|article|puzzles|lottery)/.*/)$",\n                        "^(money/(economic-calendar|etfs|funds|markets|stocks|lookup)/.*/)$",\n                        "^(blog/corrections/.*)$"\n                    ]\n                },\n                {\n                    "name": "Gift Guide",\n                    "view": "views/pages/specials/gift-guide",\n                    "urls": ["^(holiday-gift-guide/.*)$"]\n                }\n            ]\n        },\n        {\n            "name": "Interactives",\n            "appClass": "views/modules/interactivesApp",\n            "routes": [\n                {\n                    "name": "Interactive",\n                    "module": "views/modules/interactives",\n                    "view": "views/pages/interactives",\n                    "urls": ["^(interactive/.*)$"]\n                }\n            ]\n        }\n    ]\n}';});

/**

    A jQuery version of window.resizeStop.

    This creates a jQuery special event called "resizestop". This event fires after a certain number of milliseconds since the last resize event fired.

    Additionally, as part of the event data that gets passed to the eventual handler function, the resizestop special event passes the size of the window in an object called "size".

    For example:

    $(window).bind('resizestop', function (e) {
        console.log(e.data.size);
    });

    This is useful for performing actions that depend on the window size, but are expensive in one way or another - i.e. heavy DOM manipulation or asset loading that might be detrimental to performance if run as often as resize events can fire.

    @name jQuery.event.special.resizestop
    @requires jQuery 1.4.2
    @namespace

*/
(function ($, setTimeout) {

    var $window = $(window),
        cache = $([]),
        last = 0,
        timer = 0,
        size = {};

    /**
        Handles window resize events.

        @private
        @ignore
    */
    function onWindowResize() {
        last = $.now();
        timer = timer || setTimeout(checkTime, 10);
    }

    /**
        Checks if the last window resize was over the threshold. If so, executes all the functions in the cache.

        @private
        @ignore
    */
    function checkTime() {
        var now = $.now();
        if (now - last < $.resizestop.threshold) {
            timer = setTimeout(checkTime, 10);
        } else {
            clearTimeout(timer);
            timer = last = 0;
            size.width = $window.width();
            size.height = $window.height();
            cache.trigger('resizestop');
        }
    }

    /**
        Contains configuration settings for resizestop events.

        @namespace
    */
    $.resizestop = {
        propagate: false,
        threshold: 500
    };

    /**
        Contains helper methods used by the jQuery special events API.

        @namespace
        @ignore
    */
    $.event.special.resizestop = {
        setup: function (data, namespaces) {
            cache = cache.not(this); // Prevent duplicates.
            cache = cache.add(this);
            if (cache.length === 1) {
                $window.bind('resize', onWindowResize);
            }
        },
        teardown: function (namespaces) {
            cache = cache.not(this);
            if (!cache.length) {
                $window.unbind('resize', onWindowResize);
            }
        },
        add: function (handle) {
            var oldHandler = handle.handler;
            handle.handler = function (e) {
                // Generally, we don't want this to propagate.
                if (!$.resizestop.propagate) {
                    e.stopPropagation();
                }
                e.data = e.data || {};
                e.data.size = e.data.size || {};
                $.extend(e.data.size, size);
                return oldHandler.apply(this, arguments);
            };
        }
    };

})(jQuery, setTimeout);
define("resizestop", function(){});

/*
 * Sets up jquery
 */
(function($) {
    $.support.css = $.support.css || {};
    if (Modernizr.csstransitions){
        $.support.css.transition = {
            cssName: Modernizr.prefixed('transition'),
            endEventNames: {
                'WebkitTransition' : 'webkitTransitionEnd',
                'MozTransition'    : 'transitionend',
                'OTransition'      : 'oTransitionEnd',
                'msTransition'     : 'MSTransitionEnd',
                'transition'       : 'transitionend'
            }
        };
        $.support.css.transition.endName = $.support.css.transition.endEventNames[$.support.css.transition.cssName];
        $.support.css.transition.registerTransitionEndListener = function(el, deferred){
            if (!deferred){
                deferred = $.Deferred();
            }
            var transitionEndName = $.support.css.transition.endName;
            var transitionEndFunc = function transitionEnd(){
                this.removeEventListener(transitionEndName, transitionEndFunc);
                deferred.resolve();
                transitionEndFunc = null;
            };
            el.addEventListener($.support.css.transition.endName, transitionEndFunc);
            return deferred.promise();
        };
    }
    if (Modernizr.csstransforms3d &&
        // and not safari 5
        !(navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') === -1 &&
        navigator.userAgent.indexOf('Version/5') !== -1)){

        $.support.css.transform = {
            cssName: Modernizr.prefixed('transform'),
            originCssName: Modernizr.prefixed('transformOrigin'),
            styleCssName: Modernizr.prefixed('transformStyle'),
            backfaceVisibilityCssName: Modernizr.prefixed('backfaceVisibility'),
            perspectiveCssName: Modernizr.prefixed('perspective'),
            perspectiveOriginCssName: Modernizr.prefixed('perspectiveOrigin')
        };
        $.support.css.transform.cssHyphenName = $.support.css.transform.cssName.replace(/([A-Z])/g,
            function(str,m1){
                return '-' + m1.toLowerCase();
            }).replace(/^ms-/,'-ms-');
    }
})(jQuery);
define("transformSupport", function(){});

/**
 * @fileoverview Base Class providing basic functions like animate, initialize, destroy, render, show, hide
 * @author Jay Merrifield
 */
define('baseview',['jquery', 'underscore', 'backbone', 'state', 'app', 'pubsub', 'managers/trafficcop', 'easing', 'transformSupport'],
    function($, _, Backbone, StateManager, App, PubSub, TrafficCop) {

        var BaseView = Backbone.View.extend({
            // css transitions constants
            useCSSTransitions: !!$.support.css.transition,
            transEndEventNames: $.support.css.transition && $.support.css.transition.endEventNames,
            transitionCssName: $.support.css.transition && $.support.css.transition.cssName,
            transitionEndName: $.support.css.transition && $.support.css.transition.endName,
            // css transform constants
            useCSSTransforms: !!$.support.css.transform,
            transformOriginCssName: $.support.css.transform && $.support.css.transform.originCssName,
            transformCssName: $.support.css.transform && $.support.css.transform.cssName,
            transformStyleCssName: $.support.css.transform && $.support.css.transform.styleCssName,
            backfaceVisibilityCssName: $.support.css.transform && $.support.css.transform.backfaceVisibilityCssName,
            transformCssHyphenName: $.support.css.transform && $.support.css.transform.cssHyphenName,
            perspectiveCssName: $.support.css.transform && $.support.css.transform.perspectiveCssName,
            perspectiveOriginCssName: $.support.css.transform && $.support.css.transform.perspectiveOriginCssName,
            // browser detection
            isSafari: navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') === -1 &&
                                                                navigator.userAgent.indexOf('iPhone') === -1 &&
                                                                navigator.userAgent.indexOf('iPad') === -1,
            isSafari5: navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') === -1 &&
                                                                navigator.userAgent.indexOf('Version/5') !== -1,
            isApple: navigator.userAgent.indexOf('iPhone') > -1 || navigator.userAgent.indexOf('iPad') > -1,
            pubSub: null,
            options: {animations: {
                fadeIn: {
                    duration: 200,
                    easing: 'easeInQuad'
                },
                fadeOut: {
                    duration: 200,
                    easing: 'easeOutSine'
                },
                slide: {
                    duration: 350,
                    easing: 'ease-in-out'
                },
                useCSSTransitions: true
            }},

            initialize: function(options){
                this.options = $.extend(true, {}, BaseView.prototype.options, options);
                this.useCSSTransitions = (this.options.animations.useCSSTransitions && this.useCSSTransitions);
                if (!this.useCSSTransitions){
                    this.useCSSTransforms = false;
                }
                this.subviews = this.subviews || {};
                this.clear$$(); // initialize the object

                if (this.pubSub){
                    PubSub.attach(this.pubSub, this);
                }
            },

            /**
             * queries the $el for a selector and caches the result
             * @param {String} cssSelector selector to query
             * @return {jQuery}
             */
            $$: function(cssSelector){
                var dom = this.cachedSelectors[cssSelector];
                if (!dom){
                    dom = this.$(cssSelector);
                    this.cachedSelectors[cssSelector] = dom;
                }
                return dom;
            },

            /**
             * clears the cached selectors
             * @param {String} [cssSelector] optional css selector to provide, if not provided will clear all selectors
             */
            clear$$: function(cssSelector){
                if (cssSelector){
                    delete this.cachedSelectors[cssSelector];
                }else{
                    this.cachedSelectors = {};
                }
            },

            /**
             * Extra functionality added to backbone's setElement,
             * essentially clears all selectors related to the old $el
             */
            setElement: function(){
                this.clear$$();
                Backbone.View.prototype.setElement.apply(this, arguments);
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {Boolean} removeEl Option to also remove the html from the DOM.
             * @param {Boolean} paused Option to specify if the modules being destroyed are being
             *                          destroyed cause the view is being paused vs removed.
             */
            destroy: function(removeEl, paused) {
                this.destroyModules(removeEl, paused);
                this.clear$$(); // detach all dom references
                if (this.pubSub) PubSub.unattach(this.pubSub, this);
                if (removeEl) this.$el.remove();
            },
            /**
             * Destroys the subviews of this view
             * @param {Boolean} removeEl Option to of whether to remove the subview from the DOM.
             * @param {Boolean} paused Option to specify if the modules being destroyed are being
             *                          destroyed cause the view is being paused vs removed.
             */
            destroyModules: function(removeEl, paused){
                this._callCollection(this.subviews, 'destroy', [removeEl, paused]);
                this.undelegateEvents();
                this.subviews = {};
            },

            triggerEvent: function(name){
                var args = Array.prototype.slice.call(arguments, 1);
                this._callCollection(this.subviews, name, args);
            },

            _callCollection: function(collection, name, args){
                _.each(collection, function(module) {
                    // if we get an array of instances, iterate and destroy
                    try{
                        if ($.isArray(module)) {
                            _.each(module, function(m) {
                                if ($.isFunction(m[name])){
                                    m[name].apply(m, args);
                                }
                            });
                        } else if (module && $.isFunction(module[name])){
                            module[name].apply(module, args);
                        }
                    }catch(ex){
                        console.error('subview threw exception on destruction: ',
subview threw exception on destruction:  TypeError: Cannot call method 'find' of undefined
    at n.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:12567)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
    at i.View.extend._callCollection (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:662)
    at i.View.extend.destroyModules (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:427)
    at i.View.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:294)
    at o.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:24375)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
    at i.View.extend._callCollection (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:662)
subview threw exception on destruction:  TypeError: Cannot call method 'find' of undefined
    at n.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:12567)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
    at i.View.extend._callCollection (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:662)
    at i.View.extend.destroyModules (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:427)
    at i.View.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:294)
    at o.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:24375)
    at o.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:13:7955)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
subview threw exception on destruction:  TypeError: Cannot call method 'find' of undefined
    at n.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:12567)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
    at i.View.extend._callCollection (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:662)
    at i.View.extend.destroyModules (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:427)
    at i.View.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:294)
    at o.extend.destroy (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:24375)
    at http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:785
    at Function.C.each.C.forEach (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:3:28732)
    at i.View.extend._callCollection (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:6:662)
                            (ex.stack || ex.stacktrace || ex.message));
                    }
                });
            },

            registerAnimation: function(deferred, el, property, value){
                return TrafficCop.addAnimation(deferred, el, property, value);
            },

            /**************************************************************
             * Utility Transition & Animation Functions
             **************************************************************/

            slide: function(newContent, direction, timeMs, easing){
                var attribute = null;
                var endPosition = null;
                if (direction === 'left'){
                    attribute = 'left';
                    endPosition = -100;
                }else if (direction === 'right'){
                    attribute = 'left';
                    endPosition = 100;
                } //TODO 'up' and 'down'

                var offset = StateManager.getBreakingNewsOffset();
                this.$el.css(attribute, '0%');
                this.$el.css({position: 'absolute', top: offset - App.getScrollPosition()});
                newContent = $(newContent);
                newContent.css(attribute, (endPosition * -1) + '%');
                newContent.css({position: 'absolute', top: offset});
                newContent.insertAfter(this.$el);
                var deferred = $.Deferred();

                // we defer to give the browser a minute to render everything so the animation is timed better
                _.defer(_.bind(function(){
                    // if we have no element, assume someone else is handling the slide out
                    if (this.$el.length !== 0){
                        this.animate(this.$el, attribute, endPosition + '%', timeMs, easing);
                    }
                    var promise = this.animate(newContent, attribute, '0%', timeMs, easing);
                    promise.done(_.bind(function(){
                        this.$el.remove();
                        newContent.css({position: '', top: ''});
                        this.setElement(newContent);
                        deferred.resolve();
                    }, this));
                }, this));
                return deferred.promise();
            },

            /**
             * Utility function that will animate an element using css or jquery animation
             * based on the capabilities of the browser
             * @param {jQuery} el element to animate
             * @param {String} property property name to animate
             * @param {String} value property value to animate to
             * @param {Number} timeMs time in milliseconds the animation should take
             * @param {String} easing the easing algorithm to use, defaults to 'linear' if absent
             * @param {Number} [delay=0] time in milliseconds the animation should delay for
             * @return {Deferred} promise that will resolve when the animation finishes
             */
            animate: function(el, property, value, timeMs, easing, delay){
                if (!el || el.length === 0){
                    console.error('tried animating null or empty jquery object');
                    return $.Deferred().reject();
                }
                easing = easing || 'linear';
                var animationPromise = null;
                if(this.useCSSTransitions && !this.isSafari5 && !document.webkitHidden) {
                    if (delay){
                        delay = ' ' + delay + 'ms';
                    }else{
                        delay = '';
                    }
                    if (this.useCSSTransforms && (property === 'left' || property === 'top')){
                        animationPromise = this._transform(el, property, value, timeMs, easing, delay);
                    }else{
                        if (property === 'opacity'){
                            if (el.css('display') === 'none'){
                                console.error('tried animating the opacity of a display:none property', el);
                                return $.Deferred().reject();
                            }
                        }
                        animationPromise = this._transition(el, property, value, timeMs, easing, delay);
                    }
                } else {
                    if (easing.indexOf('cubic-bezier') !== -1){
                        easing = 'swing';
                    }else if (easing === 'ease-in'){
                        easing = 'easeInQuad';
                    }else if (easing === 'ease-out'){
                        easing = 'easeOutQuad';
                    }else if (easing === 'ease-in-out'){
                        easing = 'easeInOutQuad';
                    }
                    var properties = {};
                    properties[property] = value;
                    animationPromise = el.animate(properties, timeMs, easing).promise();
                }
                this.registerAnimation(animationPromise, el, property, value);
                return animationPromise;
            },
            _transition: function(el, property, toValue, timeMs, easing, delay) {
                var transitionDeferred = $.Deferred(), transitionProperty = property + ' ' + timeMs + 'ms ' + easing + delay;
                if (timeMs === 0) { // special case 0, we don't want the delay the change
                    el.css(property, toValue);
                    transitionDeferred.resolve();
                } else {
                    var origValue = el.css(property), sanitizedToValue = (toValue + '').replace(/[px ]/g, '');
                    // if the value isn't changing, resolve immediately, otherwise the transition end listener won't fire
                    if (parseFloat(toValue) === parseFloat(origValue) || sanitizedToValue === origValue.replace(/[px ]/g, '')) {
                        transitionDeferred.resolve();
                    } else {
                        if (el[0].style[this.transitionCssName]) {
                            el[0].style[this.transitionCssName] += ',' + transitionProperty;
                        } else {
                            el[0].style[this.transitionCssName] = transitionProperty;
                        }
                        // adding a quick delay guarantees that the timing of the function is more accurate
                        // it also improves animation in firefox
                        $.Deferred(_.bind(function(defer) {
                                _.delay(_.bind(function() {
                                    this.registerTransitionEndListener(el, defer);
                                    el.css(property, toValue);
                                }, this));
                            }, this)).done(_.bind(function() {
                                // verify that we actually ended up where we wanted to end up so we don't accidentally call the wrong success handler
                                if (parseFloat(toValue) === parseFloat(el.css(property)) || sanitizedToValue === el.css(property).replace(/[px ]/g, '')) {
                                    transitionDeferred.resolve();
                                } else {
                                    transitionDeferred.reject();
                                }
                                el[0].style[this.transitionCssName] = $.trim(el[0].style[this.transitionCssName].replace(new RegExp(transitionProperty + '[^,]*'), '').replace(/^[ ,]+/, '').replace(/[ ,]+$/, '').replace(/,[ ]+,/, ''));
                            }, this));
                    }
                }
                return transitionDeferred.promise();
            },
            _transform: function(el, property, value, timeMs, easing, delay) {
                var transitionDeferred = $.Deferred();
                var transitionValue = this.transformCssHyphenName + ' ' + timeMs + 'ms ' + easing + delay;
                var translateValue = this._buildTranslate3d(property, value);
                // convert non-transform properties into a transform property
                var existingPropertyValue = el.css(property);
                if (existingPropertyValue && existingPropertyValue !== '0px') {
                    el[0].style[this.transformCssName] = this._buildTranslate3d(property, existingPropertyValue);
                    el.css(property, 'auto');
                }
                if (timeMs === 0) { // special case 0, we don't want the delay the change
                    el[0].style[this.transitionCssName] = transitionValue;
                    el[0].style[this.transformCssName] = translateValue;
                    transitionDeferred.resolve();
                } else {
                    // if the value isn't changing, resolve immediately, otherwise the transition end listener won't fire
                    var origValue = el[0].style[this.transformCssName] || '';
                    if (translateValue.replace(/[px ]/g, '') === origValue.replace(/[px ]/g, '')) {
                        transitionDeferred.resolve();
                    } else {
                        $.Deferred(_.bind(function(defer) {
                                // adding a quick delay guarantees that the timing of the function is more accurate
                                // it also improves animation in firefox
                                _.delay(_.bind(function() {
                                    this.registerTransitionEndListener(el, defer);
                                    el[0].style[this.transitionCssName] = transitionValue;
                                    el[0].style[this.transformCssName] = translateValue;
                                }, this));
                            }, this)).done(_.bind(function() {
                                // verify that we actually ended up where we wanted to end up so we don't accidentally call the wrong success handler
                                if (el[0].style[this.transformCssName].replace(/[px ]/g, '') === translateValue.replace(/[px ]/g, '')) {
                                    transitionDeferred.resolve();
                                } else {
                                    transitionDeferred.reject();
                                }
                            }, this));
                    }
                }
                transitionDeferred.done(_.bind(function() {
                    this.clearTransition(el);
                    el.css(property, value);
                }, this));
                return transitionDeferred.promise();
            },
            _buildTranslate3d: function(property, value){
                var translate = 'translate3d(';
                if (property === 'left'){
                    translate += value;
                }else{
                    translate += '0';
                }
                translate += ',';
                if (property === 'top'){
                    translate += value;
                }else{
                    translate += '0';
                }
                translate += ',0)';
                return translate;
            },

            clearTransition: function(){
                if (this.useCSSTransitions){
                    $(arguments).each(_.bind(function(idx, el){
                        if (!el){
                            return;
                        }
                        if (el instanceof $){
                            el = el[0];
                        }
                        el.style[this.transitionCssName] = '';
                        if (this.useCSSTransforms){
                            el.style[this.perspectiveCssName] = '';
                            el.style[this.perspectiveOriginCssName] = '';
                            el.style[this.backfaceVisibilityCssName] = '';
                            el.style[this.transformCssName] = '';
                            el.style[this.transformStyleCssName] = '';
                            el.style[this.transformOriginCssName] = '';
                        }
                    }, this));
                }
            },

            registerTransitionEndListener: function($el, deferred){
                if ($.support.css.transition){
                    return $.support.css.transition.registerTransitionEndListener($el[0], deferred);
                }else{
                    return $.Deferred.reject();
                }
            },

            /**
             * Show the 'el'. Optionally by fading them in.
             * @param {Boolean} transition Fade in the element.
             * @param {Function} legacyCallback deprecated callback function
             * @return {jQuery Promise Object} that will resolve when the animation finishes
             */
            show: function(transition, legacyCallback) {
                var promise = null;
                if(transition && !this.isSafari5) {
                    promise = this.$el.fadeTo(
                        this.options.animations.fadeIn.duration,
                        1,
                        this.options.animations.fadeIn.easing
                    ).promise();
                    this.registerAnimation(promise, this.$el, 'opacity', 1);
                } else {
                    //we set the css directly instead of calling jquery to avoid
                    // a css recalculation triggered by jquery
                    promise = $.Deferred().resolve();
                    this.$el.css({display: 'block', opacity: 1});
                }
                promise.done(function(){
                    if (legacyCallback){
                        legacyCallback();
                    }
                });
                return promise;
            },

            /**
             * Hide the cards. Optionally by fading them out.
             * @param {Boolean} transition Fade out the element.
             * @param {Function} legacyCallback deprecated callback function
             * @return {jQuery Promise Object} that will resolve when the animation finishes
             */
            hide: function(transition, legacyCallback) {
                var promise = null;
                if(transition && !this.isSafari5) {
                    promise = this.$el.fadeTo(
                        this.options.animations.fadeOut.duration,
                        0,
                        this.options.animations.fadeOut.easing
                    ).promise();
                    // jquery sets display: block on anything it's fading, but we want the end result to be gone
                    promise.done(_.bind(function(){
                        this.$el.css({display: 'none'});
                    }, this));
                    this.registerAnimation(promise, this.$el, 'opacity', 0);
                } else {
                    //we set the css directly instead of calling jquery to avoid
                    // a css recalculation triggered by jquery
                    promise = $.Deferred().resolve();
                    this.$el.css({display: 'none', opacity: 0});
                }
                promise.done(function(){
                    if (legacyCallback){
                        legacyCallback();
                    }
                });
                return promise;
            }
        });

        return BaseView;
    }
);
/**
 * @fileoverview Ad Logging singleton
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 * @author cdshryock@gannett.com (Chad Shryock)
 */
define('adLogger',[
    'app',
    'underscore'
],
function(App, _) {
    

    var AdLogger = function(){
        this.initialize();
    };
    AdLogger.prototype = {
        initialize: function(){
            this.isIE = navigator.appName === 'Microsoft Internet Explorer';
            this.debug = window.isAdDebug || App.getUrlParam('usat_console') === '1';
            // polyfill for IE8/9 which treats console.XXX as objects instead of functions so we can't do .apply below
            if (Function.prototype.bind && window.console && typeof window.console.log === "object") {
                _.each(["log","info","warn","error"], function (method) {
                    window.console[method] = Function.prototype.call.bind(window.console[method], window.console);
                });
            }
        },

        _log: function(msg, type, args){
            if (window.console && window.console[type]) {
                window.console[type].apply(window.console, _.union([('Ad ' + type + ': ' + msg)], args));
Ad error: Site Url changed, but ad placements were not released:  Object
Ad warn: Advertisement viewport is too small: 540x390
Ad error: Site Url changed, but ad placements were not released:  Object
Ad error: Ad threw an exception in function onStopToClose TypeError: Cannot read property 'player' of undefined
    at Object.privateMethods.youTubeMute (http://i.usatoday.net/adsolutions/_common/ad-video/jquery.ad-video_ui_1.10.2.js?v=UX-HotFix-43:412:30)
    at HTMLDivElement.<anonymous> (http://i.usatoday.net/adsolutions/_common/ad-video/jquery.ad-video_ui_1.10.2.js?v=UX-HotFix-43:152:32)
    at Function.Q.extend.each (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:1:14566)
    at Q.fn.Q.each (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:1:11299)
    at methods.mute (http://i.usatoday.net/adsolutions/_common/ad-video/jquery.ad-video_ui_1.10.2.js?v=UX-HotFix-43:148:25)
    at $.fn.adVideo (http://i.usatoday.net/adsolutions/_common/ad-video/jquery.ad-video_ui_1.10.2.js?v=UX-HotFix-43:693:36)
    at BaseView.extend.onStopToClose (http://pagead2.googlesyndication.com/pagead/imgad?id=CICAgIDQhaXMgAEQARgBMgisK9IMilaSVQ&v=UX-HotFix-43:94:29)
    at i.extend._dispatchToPartner (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:9:6384)
    at i.extend.stopAd (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:9:6594)
    at n.extend.closeAd (http://www.gannett-cdn.com/static/jsb/main.js?v=UX-HotFix-43:12:16390)
                if (this.isIE) {
                    for (var i = 0, j = args.length; i < j; i++) {
                        window.console[type]('|- ' + args[i]);
                    }
                }
            }
        },

        logDebug : function(msg) {
            if (this.debug){
                this._log(msg, 'log', Array.prototype.slice.call(arguments, 1));
            }
        },

        logError : function(msg) {
            this._log(msg, 'error', Array.prototype.slice.call(arguments, 1));
        },

        logInfo : function(msg) {
            if (this.debug){
                this._log(msg, 'info', Array.prototype.slice.call(arguments, 1));
            }
        },

        logWarn : function(msg) {
            this._log(msg, 'warn', Array.prototype.slice.call(arguments, 1));
        }
    };
    return new AdLogger();
});
/**
 * @fileoverview Our wrapper around gpt's ad slot, includes monitoring the slot and event capture
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
/*global googletag:true*/
define('views/modules/partner/ad-slot',[
    'jquery',
    'underscore',
    'baseview',
    'adLogger'
],
function(
    $,
    _,
    BaseView,
    AdLogger
) {
    
    /**
     * View class.
     */
    var AdSlot = BaseView.extend({
        className: 'ad-slot',
        id: function() {
            return _.uniqueId('ad-slot-' + this.options.adUnit.replace(/\//g, '-') + '-');
        },

        events: {
            'partnersetup': 'onHighImpactAdLoad'
        },

        initialize: function(options) {
            options = $.extend({
                adUnit: null, // required parameter!!
                targeting: {},
                sizes: [], // ad sizes for this slot
                type: 'in',
                onSlotRender: null,
                position: null // required!
            }, options);
            options.position.append(this.$el);
            // when you don't provide an el, delegateEvents doesn't fire by default, so fire it after placing it on the dom

            this.gptSlot = null;
            this.slotId = this.$el.prop('id');
            this.adDeliveryData = null;

            BaseView.prototype.initialize.call(this, options);

            if (this.options.type === 'in') {
                this._registerSlotWithGoogle(this.options.adUnit, this.options.sizes, this.slotId, this.options.targeting);
            } else {
                this._registerOutOfPageSlotWithGoogle(this.options.adUnit, this.slotId, this.options.targeting);
            }
        },

        destroy: function() {
            this.adData = null;
            this.gptSlot = null;
            BaseView.prototype.destroy.call(this, true);
        },

        refresh: function() {
            this.adData = null;
            if (!this.gptSlot) {
                AdLogger.logError('attempted to refresh slot with no gptSlot');
            } else if (window.googletag) {
                googletag.cmd.push(_.bind(function() {
                    googletag.pubads().refresh([this.gptSlot]);
                    AdLogger.logInfo('Ad refreshed for slot', this.gptSlot);
                }, this));
            }
        },

        onHighImpactAdLoad: function(event, params) {
            var adData = null;
            if (params && params.data) {
                adData = params.data;
            } else if (event.originalEvent && event.originalEvent.data) {
                adData = event.originalEvent.data;
            } else {
                AdLogger.logError('AdSlot(' + this.options.adUnit + '): Found a high impact ad, can\'t find the data object from the iFrame', arguments);
                return;
            }
            if (!adData || !adData.adType) {
                AdLogger.logError('AdSlot(' + this.options.adUnit + '): high impact event received, but invalid data object was given', adData);
                return;
            }
            this.adData = adData;
            var adType = this._normalizeAdType(adData.adType);
            this.options.onSlotRender(adData, adType);
        },

        _normalizeAdType: function(adType) {
            if (!adType) {
                return null;
            } else if (adType === 'Live Feed Takeover') {
                return 'livefeed';
            } else {
                return adType.toLowerCase().replace(/[^a-z]/, '');
            }
        },

        _registerOutOfPageSlotWithGoogle: function(adUnit, slotId, targeting) {
            if (!window.googletag) {
                return;
            }
            googletag.cmd.push(_.bind(function() {
                AdLogger.logInfo('AdSlot(' + this.options.adUnit + '): registering out of page slot with google ' + adUnit);
                this.gptSlot = googletag.defineOutOfPageSlot(adUnit, slotId).addService(googletag.pubads());
                this._setTargeting(this.gptSlot, targeting);
                // this command makes no sense, but slots don't work without it
                googletag.display(slotId);
                this._setupSlotRenderedCallback(this.gptSlot);
                googletag.pubads().refresh([this.gptSlot]);
            }, this));
        },

        _registerSlotWithGoogle: function(adUnit, sizes, slotId, targeting) {
            if (!window.googletag) {
                return;
            }
            googletag.cmd.push(_.bind(function() {
                AdLogger.logInfo('AdSlot(' + this.options.adUnit + '): registering slot with google ' + adUnit + ' sizes', sizes);
                this.gptSlot = googletag.defineSlot(adUnit, sizes, slotId).addService(googletag.pubads());
                this._setTargeting(this.gptSlot, targeting);
                // this command makes no sense, but slots don't work without it
                googletag.display(slotId);
                this._setupSlotRenderedCallback(this.gptSlot);
                googletag.pubads().refresh([this.gptSlot]);
            }, this));
        },

        _setupSlotRenderedCallback: function(gptSlot) {
            // swap out the gpt slot's renderEnded function with our own so we're notified when the ad is delivered
            var origRenderEnded = gptSlot.renderEnded;
            gptSlot.renderEnded = _.bind(function() {
                var iframe = this.$('iframe').eq(0);
                if (this.gptSlot && !this.adData && this.$el.css('display') !== 'none') {
                    // this is for IAB ads, gpt usually hides $el if there's no ad, but sometimes it delivers a tiny little ad we should ignore
                    if (parseInt(iframe.prop('width'), 10) > 10 && parseInt(iframe.prop('height'), 10) > 10) {
                        this.options.onSlotRender();
                    }
                }
                origRenderEnded.apply(gptSlot, arguments);
            }, this);
        },

        setTargeting: function(targeting) {
            if (this.gptSlot) {
                this.gptSlot.clearTargeting();
                this._setTargeting(this.gptSlot, targeting);
            }
        },

        _setTargeting: function(gptSlot, targeting) {
            _.each(targeting, function(value, key) {
                if (value) {
                    gptSlot.setTargeting(key, value);
                    AdLogger.logInfo('AdSlot(' + this.options.adUnit + '): set targetting - key:' + key + ' value:' + value);
                }
            }, this);
        }
    });
    return AdSlot;
});
/*!
 * jQuery Cookie Plugin
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);

define("cookie", function(){});

/*global googletag:true,Modernizr:true*/
define('admanager',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'views/modules/partner/ad-slot',
    'adLogger',
    'cookie'
],
function(
    $,
    _,
    Backbone,
    App,
    AdSlot,
    AdLogger
) {
        
        var AdManager = function(){
            this.initialize();
        };
        AdManager.prototype = {

            /* Comscore Monetization is a project to decide how we should place our ads
             * we have Comscore monitor "ad zones" for visibility
             * an "ad zone" is a rectangle where we might display an ad in the future
             * an ad zone is any element in the DOM with class partner-placement and attribute data-monetization-id and attribute data-monetization-sizes
             * initial draft: treat ad slots as ad zones
             * potential future: maybe use a new system for monetization size names
             * potential future: place ad zones where we have no ad slot
             */
            setMonetization: function($el, monetizationId, monetizationSizes) {
                if (!$el.attr) return; // FIXME: how can $el not have .attr() ?
                $el.attr('data-monetization-id', monetizationId.replace(/\/.*/, ''));
                $el.attr('data-monetization-sizes', monetizationSizes.join(','));
            },

            adSizes : {
                'pushdown' : [1200,615],
                'elastic' : [1080,810],
                'outofpage' : [1080,810],
                'cinematicvideoskin' : [2600,1400],
                'heroflip' : [720,524],
                'livefeed' : [300,800],
                'videotakeover' : [720,405],
                'coverviewfullpage' : [1,1],
                'mediumrectangle' : [300,250],
                'halfpage' : [300,600],
                'leaderboard' : [728,90], // FERCKIN SPERTS
                // rising star ad types
                'filmstrip': [300,600],
                'iabpushdown': [970,90],
                'iabpushdown2': [970,66],
                'billboard': [970,250],
                'portrait': [300,1050],
                'sponsor_logo': [100,30]
            },
            noAds: false,
            // map of adUnit to a list of placements
            activeAdPlacements: {},

            /**
             * Retrieves a shared ad slot that has multiple possible output positions
             * @param {String} adPlacement name of the dfp placement targeting
             * @param {Object} targeting key/value custom targeting map
             * @param {Object} positionMap key/value mapping of adType{String} -> adPosition
             * @param {Object} defaultPosition the default position if no high impact ad is delivered
             * @param {String} [slotType=in] google slot type, either 'out' or 'in'
             * @return {Object} new AdSlot
             */
            getSharedAdSlot: function(adPlacement, targeting, positionMap, defaultPosition, slotType) {
                var adSizes = this._buildAdSizesFromPlacements(positionMap),
                    adUnit = this.buildAdUnit(adPlacement, targeting),
                    adPosition = (defaultPosition && defaultPosition.$el) || this.globalStaging;
                this.setMonetization(adPosition, adPlacement, _.keys(positionMap));
                return new AdSlot({
                    adUnit: adUnit,
                    targeting: targeting,
                    sizes: adSizes,
                    type: slotType || (defaultPosition && defaultPosition.getSlotType()) || 'in',
                    position: adPosition,
                    onSlotRender: function(adData, adType) {
                        if (!adType) {
                            defaultPosition.render();
                        } else {
                            var adPosition = positionMap[adType];
                            if (!adPosition) {
                                AdLogger.logError('AdSlot(' + adUnit + '): ad delivered to unknown ad position/type: ' + adType);
                                return;
                            }
                            adPosition.render(adData, adType);
                        }
                    }
                });
            },
            /**
             * Builds an ad slot wrapper around google's ad slots
             * @param {String} adPlacement name of the dfp placement targeting
             * @param {Object} targeting key/value custom targeting map
             * @param {String[]} adPlacementSizes ad size names
             * @param {Object} adPosition Object that will handle the ad slot
             * @param {String} [slotType=out] google slot type, either 'out' or 'in'
             * @return {Object} new AdSlot
             */
            getAdSlot: function(adPlacement, targeting, adPlacementSizes, adPosition, slotType){
                var adUnit = this.buildAdUnit(adPlacement, targeting),
                    adRequestSizes = this._mapAdSizeNamesToActualSizes(adPlacementSizes);
                this.setMonetization(adPosition, adPlacement, adPlacementSizes);
                return new AdSlot({
                    adUnit: adUnit,
                    targeting: targeting,
                    sizes: adRequestSizes,
                    type: slotType || 'out',
                    position: adPosition.$el,
                    onSlotRender: function(adType, adData) {
                        adPosition.render(adType, adData);
                    }
                });

            },

            /**
             * Given an ad placement and optional custom targeting map, will build an ad unit string
             * with either the current accountId and Name, or the overridden ones.
             * If an ad label override is supplied, it'll be added to the targeting map
             * @param {String} adPlacement name of the ad placement for the ad unit
             * @param {Object} [targeting] targeting key value map
             * @return {String}
             */
            buildAdUnit: function(adPlacement, targeting){
                // Build the adUnit Path
                var args = {
                    'accountId' : window.site_config.ADS.DFP.ACCOUNTID,
                    'accountName' : window.site_config.ADS.DFP.ACCOUNTNAME,
                    'adUnit' : adPlacement
                };
                if (this.override) {
                    args.accountId = this.override.usatai;
                    args.accountName = this.override.usatan;
                    if (targeting) {
                        targeting.adlabel = this.override.usatl;
                    }
                }
                return args.accountId + '/' + args.accountName + '/' + args.adUnit;
            },

            /**
             * Returns the size array for an ad unit
             * @param adUnit - name of an ad unit
             */
            getSize : function(adUnit) {
                var size = this.adSizes[adUnit];
                if (!size) {
                    AdLogger.logWarn('Size not found for ' + adUnit);
                    return null;
                }
                return size;
            },

            /**
             * Gets the size for the vCE tag
             * @param adType (Pushdown, Hero Flip, Live Feed Takeover, Elastic)
             */
            getVCESize : function(adType) {
                var sa = this.getSize(adType);
                if (!sa) {
                    return '1x1';
                }
                return sa.join('x');
            },

            /**
             * Kickoff
             */
            initialize :  function() {
                if (!window.googletag) {
                    this.noAds = true;
                    return;
                }

                AdLogger.logDebug('AdManager initializing');

                var usatai = App.getUrlParam('usatai'),
                    usatan = App.getUrlParam('usatan'),
                    usatl = App.getUrlParam('usatl');
                if (usatai && usatan && usatl){
                    this.override = {
                        usatai: usatai,
                        usatan: usatan,
                        usatl: usatl
                    };
                }

                this.globalStaging = $('#ad-staging');

                // init the Google stuff
                this._initializeGoogletag();
                window.adManager = this;

                // init base targeting
                this._initializeBaseTargeting();

                AdLogger.logDebug('AdManager initialize', this);
            },

            /**
             * Configures the Google services
             * @private
             */
            _initializeGoogletag: function() {
                googletag.cmd.push(function() {
                    AdLogger.logInfo('Collapses the empty divs. Used for the asset pages where the slot and placement are the same');
                    googletag.pubads().collapseEmptyDivs();

                    // this forces us to call refresh on each slot, so we get a unique correlator value
                    AdLogger.logInfo('Disabling initial load of slots');
                    googletag.pubads().disableInitialLoad();

                    AdLogger.logInfo('Enabled the ad calls');
                    googletag.enableServices();
                });
            },

            /**
             * Sets the base targeting, keywords and RevSci
             * @private
             */
            _initializeBaseTargeting: function() {
                var pubads = googletag.pubads();
                googletag.cmd.push(function() {
                    // Adobe Audience Manager
                    var aam= (($.cookie('aamusat')||'').match(/[0-9]+/g)||[]).join(',');
                    var aid= $.cookie('aam_uuid')||'';
                    pubads.setTargeting('aam', aam);
                    pubads.setTargeting('u', aid);
                    // RevSci
                    var rawRs = $.cookie('rsi_segs');
                    if (rawRs) {
                        var rawRsArray = rawRs.split('|');
                        AdLogger.logInfo('set revsci targeting', rawRsArray);
                        pubads.setTargeting('segments', rawRsArray);
                    }

                    // set environment tracking
                    var environmentTarget = window.site_config.ADS.DFP.ENV;
                    AdLogger.logInfo('using env targeting', environmentTarget);
                    pubads.setTargeting('env', environmentTarget);
                });
            },

            /**
             * Requests ads for the shared ad placement only
             * @param {Object} pageInfo key value map that represents the current asset information we're targeting
             * @param {Object} clientAdInfo extra key/value information that is added to the targeting map
             */
            requestAds: function(pageInfo, clientAdInfo){
                var targeting = $.extend(this.getPageTargeting(pageInfo), clientAdInfo);
                var aws = '/' + pageInfo.aws; // ad unit targeting to aws section

                AdLogger.logInfo('AdManager: requestAds()', targeting);

                _.each(this.activeAdPlacements, function(adPlacementInfo) {
                    if (adPlacementInfo){
                        adPlacementInfo.slotInfo = this.getSharedAdSlot(adPlacementInfo.name + aws, targeting, adPlacementInfo.positionMap, adPlacementInfo.defaultPosition);
                    }
                }, this);
            },

            /**
             * Given a list of ad size names, will return a list of the google tag pixel size arrays
             * @param {Array.<String>} adSizeNames
             * @returns {Array}
             * @private
             */
            _mapAdSizeNamesToActualSizes: function(adSizeNames){
                var adSizes = [];
                _.each(adSizeNames, function(adSizeName){
                    var size = this.adSizes[adSizeName];
                    if (!size) {
                        AdLogger.logWarn('invalid ad size found', adSizeName);
                    }else{
                        adSizes.push(size);
                    }
                }, this);
                return adSizes;
            },

            _buildAdSizesFromPlacements: function(placementList){
                var adSizes = [];
                _.each(placementList, function(placement){
                    var sizes = this._mapAdSizeNamesToActualSizes(placement.getAdSizes());
                    $.merge(adSizes, sizes);
                }, this);
                return _.uniq(adSizes);
            },

            /**
             * Takes a pageInfo object and returns a targeting map for ads
             * @param {Object} pageInfo an object representing information about the current asset the ad is targeting
             * @return {Object} the dfp targeting map
             */
            getPageTargeting: function(pageInfo){
                var sitePage = 'usat/' + pageInfo.ssts;
                if (pageInfo.templatename === 'fronts/default' && pageInfo.section_name !== 'home') {
                    sitePage += '/front';
                }
                var targeting = {
                    'pageType' : pageInfo.basePageType,
                    'series' : pageInfo.series,
                    'sitepage' : sitePage,
                    'title' : pageInfo.seotitletag,
                    'topic' : pageInfo.topic
                };
                return targeting;
            },

            /**
             * Refreshes a shared ad placement
             * @param {String} adPlacement name of the adPlacement to refresh
             */
            refreshSharedAdPosition: function(adPlacement) {
                var adPlacementInfo = this.activeAdPlacements[adPlacement];
                if (!adPlacementInfo){
                    AdLogger.logError('AdManager: tried refreshing shared ad position that no longer exists');
                    return;
                }
                adPlacementInfo.slotInfo.refresh();
            },

            /**
             * Registers a shared ad position. Shared ad positions are a position on the page who's targeting
             * is shared with other ad positions and needs secondary information delivered by the ad
             * to target where on the page the ad is delivered.
             * @param {{getAdPlacement(): String, getAdType(): String, isDefaultPosition(): Boolean}} adObj shared ad position that has a possibility of being filled by the slot
             */
            registerSharedAdPosition: function(adObj) {
                // adUnits of the same name map to a slot
                var adPlacement = adObj.getAdPlacement(),
                    adTypes = adObj.getAdType(),
                    siteUrl = Backbone.history.getFragment();

                if (siteUrl !== this.siteUrl) {
                    this.siteUrl = siteUrl;
                    _.each(this.activeAdPlacements, function(adPlacementInfo) {
                        if (adPlacementInfo) {
                            AdLogger.logError('Site Url changed, but ad placements were not released: ', adPlacementInfo);
                        }
                    });
                    this.activeAdPlacements = {};
                }

                if (adTypes && !_.isArray(adTypes)){
                    adTypes = [adTypes];
                }
                if (!adPlacement || !adTypes || !adTypes.length) {
                    AdLogger.logError('AdManager: invalid ad unit registered, adUnit and adType are required', adObj);
                    return;
                }
                var adPlacementInfo = this.activeAdPlacements[adPlacement];
                if (!adPlacementInfo){
                    this.activeAdPlacements[adPlacement] = adPlacementInfo = {
                        name: adPlacement,
                        positionMap: {},
                        defaultPosition: null,
                        slotInfo: null,
                        numPositions: 0
                    };
                }
                _.each(adTypes, function(adType){
                    if (adPlacementInfo.positionMap[adType]){
                        AdLogger.logError('AdManager: invalid ad unit registered, duplicate adType registered', adObj);
                        return;
                    }
                    AdLogger.logInfo('AdManager: registerSharedAdPosition for adPlacement: ' + adPlacement + ' and adType:' + adType);
                    adPlacementInfo.positionMap[adType] = adObj;
                });
                adPlacementInfo.numPositions++;
                if (adObj.isDefaultPosition()){
                    if (adPlacementInfo.defaultPosition){
                        AdLogger.logWarn('AdManager: multiple ad placements declared themselves default for adUnit: ' + adPlacement, adObj);
                    }else{
                        adPlacementInfo.defaultPosition = adObj;
                    }
                }
            },

            /**
             * Removes an ad position from the placement list for delivery of ads
             * @param {{getAdPlacement(): String, getAdType(): String, isDefaultPosition(): Boolean}} adObj Shared Ad Position that was registered by registerSharedAdPosition
             */
            destroySharedAdPosition: function(adObj) {
                var adPlacementName = adObj.getAdPlacement(),
                    adTypes = adObj.getAdType(),
                    adPlacementInfo = this.activeAdPlacements[adPlacementName];
                if (!adPlacementInfo){
                    AdLogger.logError('AdManager: destruction of unknown ad unit', adObj);
                    return;
                }
                if (adTypes && !_.isArray(adTypes)){
                    adTypes = [adTypes];
                }
                _.each(adTypes, function(adType){
                    var position = adPlacementInfo.positionMap[adType];
                    if (!position){
                        AdLogger.logError('AdManager: destruction of unknown ad type', adObj);
                        return;
                    }
                    AdLogger.logInfo('AdManager: destroySharedAdPosition for adPlacement: ' + adPlacementName + ' and adType:' + adType);
                    adPlacementInfo.positionMap[adType] = null;
                });

                if (adObj.isDefaultPosition()){
                    adPlacementInfo.defaultPosition = null;
                }

                adPlacementInfo.numPositions--;
                if (!adPlacementInfo.numPositions){
                    if (adPlacementInfo.slotInfo){
                        adPlacementInfo.slotInfo.destroy();
                    }
                    this.activeAdPlacements[adPlacementName] = null;
                }
            },

            // legacy ad proxy calls

            /**
             * Deprecated createScript call. Left for VCE compatibility and ad calls that require it
             * @deprecated
             * @param {String} id id for the script tag
             * @param {String} src url for the script
             * @param {jQuery} $el jquery element for where the append the script tag
             */
            _createScript: function(id, src, $el) {
                AdLogger.logDebug('Creating script', id, src, $el[0]);
                var script = document.createElement('script');
                script.id = id;
                script.src = src;
                script.type = 'text/javascript';
                script.defer = false;
                // required to be appendChild for vce compatibility
                $el[0].appendChild(script);
            },

            logDebug: function() {
                AdLogger.logDebug.apply(AdLogger, arguments);
            },

            logError: function() {
                AdLogger.logError.apply(AdLogger, arguments);
            },

            logInfo: function() {
                AdLogger.logInfo.apply(AdLogger, arguments);
            },

            logWarn: function() {
                AdLogger.logWarn.apply(AdLogger, arguments);
            }
        };

        return new AdManager();

    }
);

/**
 * @fileoverview Base App providing basic function like revealApp, removeApp, changePage
 * An app is a stateful container that could persist between url changes. When an app is active, it
 * owns all the interactions of the markup on the page. A page is a stateless child of an app, and
 * corresponds with a single unique path that will be destroyed when changing to a new path.
 * Examples:
 *     App: Cards, Page: GenericSection
 *     App: Overlay, Page: Story
 * @author Jay Merrifield
 */
define('baseappview',['jquery',
    'underscore',
    'baseview',
    'state',
    'managers/trafficcop',
    'app',
    'pubsub',
    'admanager'
],
    function($, _, BaseView, StateManager, TrafficCop, App, PubSub, AdManager) {
        
        var BaseAppView = BaseView.extend({
            currentPath: '',

            initialize: function(options){
                this._animId = 0;
                this.$top = App.get('scrollEl');
                this.appRevealed = false;
                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },

            destroy: function(removeEl){
                // call base class initialize
                BaseView.prototype.destroy.call(this, removeEl);
            },

            /**
             * This returns true or false depending on whether the app has successfully revealed itself
             * @return {Boolean}
             */
            isRevealed: function(){
                return this.appRevealed;
            },

            /**
             * This is a function that will decide how to animate the reveal of this app
             * @param {String} fromPath path of the view going away
             * @param {String} toPath path of the view we're going to
             * @param {Deferred} requestPromise Promise object that will resolve the ajax request is complete
             * @param {Deferred} resourcePromise Promise object that will resolve when the module request is complete
             * @param {Boolean} [paused] variable specifying if the view should load up in a paused state
             * @return {Deferred} promise object that will resolve when reveal is complete
             */
            revealApp: function(fromPath, toPath, requestPromise, resourcePromise, paused) {
                // so we are going to find ourselves in a couple of scenarios here,
                // 1: requestPromise is null, cause it's an initial render, very little to do
                // 2: requestPromise has resolved with the html we want to render, animate directly to html
                // 3: requestPromise isn't ready, but we have an Reveal App Loader, animate in the loader, cross fade to final content!
                // 4: requestPromise isn't ready, and there is no reveal app loader, wait until request is done, cross fade to final content
                var requestInfo = {
                    fromPath: fromPath,
                    toPath: toPath,
                    animId: this._animId,
                    resourcePromise: resourcePromise,
                    paused: paused
                };
                this.currentPath = toPath;
                if (!requestPromise) {
                    // scenario 1, initial load, yippy!
                    this._triggerBeforePageReveal(null, requestInfo);
                    this._triggerAfterPageReveal(requestInfo);
                    return $.Deferred().resolve();
                } else if (requestPromise.state() === 'rejected') {
                    return requestPromise;
                } else {
                    // we have a request which will eventually contain new html
                    var revealCompleteDeferred = $.Deferred();
                    if (requestPromise.state() === 'resolved') {
                        // scenario 2, we have html to render immediately, go go captain planet
                        requestPromise.done(_.bind(function(htmlFrag) {
                            this._revealAppMarkup(htmlFrag, requestInfo, revealCompleteDeferred);
                        }, this));
                    } else {
                        var loaderHtml = this.getRevealAppLoader(toPath);
                        if (loaderHtml) {
                            // scenario 3, render reveal app loader
                            if (!(loaderHtml instanceof $)){
                                loaderHtml = $(loaderHtml);
                            }
                            this._revealAppMarkup(loaderHtml, requestInfo, revealCompleteDeferred, requestPromise);
                        } else {
                            // scenario 4, we have to wait on a generic loader, sad panda!
                            this._triggerGenericLoader(requestPromise);
                            requestPromise.done(_.bind(function(htmlFrag) {
                                this._revealAppMarkup(htmlFrag, requestInfo, revealCompleteDeferred);
                            }, this));
                        }
                        requestPromise.fail(function(){
                            revealCompleteDeferred.reject();
                        });
                    }
                    return revealCompleteDeferred.promise();
                }
            },

            /**
             * inserts the app  markup in a hidden & undelegated state
             * @param {jQuery} htmlFrag the dom to be loaded
             * @param {Boolean} paused specifying whether the markup is being loaded in a paused/preloaded state
             */
            _insertAppMarkup: function(htmlFrag, paused){
                htmlFrag.hide();
                this.setElement(htmlFrag, false);
                this.$el.insertAfter('#header');
                if (paused){
                    this.setFixedPosition(StateManager.getBreakingNewsOffset());
                }
            },

            /**
             * Triggers an internal page transition
             * @param {String} fromPath path of the view going away
             * @param {String} toPath path of the view we're going to
             * @param {Deferred} requestPromise Promise object that will resolve the ajax request is complete
             * @param {Deferred} resourcePromise Promise object that will resolve when the module request is complete
             * @param {Boolean} [paused] variable specifying if the view should load up in a paused state
             * @return {Deferred} promise object that will resolve when changePage is complete
             */
            changePage: function(fromPath, toPath, requestPromise, resourcePromise, paused){
                var requestInfo = {
                    fromPath: fromPath,
                    toPath: toPath,
                    animId: ++this._animId,
                    resourcePromise: resourcePromise,
                    paused: paused
                };
                // destroy existing modules so new ones can be instantiated
                // this function is up for debate, when does this get called? who's responsible for calling it?
                this.destroyModules();

                var animationPromise = null;
                if (requestPromise){
                    animationPromise = this.animateChangePagePreData(fromPath, toPath);
                }
                this.currentPath = toPath;
                if (!animationPromise){
                    // no animationPromise, generally section -> sub section, or closing overlay/fullscreen
                    if (requestPromise){
                        // we're requesting new information that needs to be swapped in
                        this._triggerGenericLoader(requestPromise);
                        return this._finishChangePage(requestPromise, requestInfo);
                    } else {
                        // No request, no animationPromise, means markup is in the correct place for the path, just need to initialize the JS
                        return this._triggerAfterPageReveal(requestInfo);
                    }
                } else {
                    if (requestPromise){
                        animationPromise = $.when(requestPromise, animationPromise);
                    }
                    return this._finishChangePage(animationPromise, requestInfo);
                }
            },
            /**
             * Sets up the overridable global loader for the request in progress
             * @param {Deferred} requestPromise promise representing the ajax request
             * @private
             */
            _triggerGenericLoader: function(requestPromise){
                if (requestPromise.state() === 'pending'){
                    this.activateLoader();
                    requestPromise.always(_.bind(function(){
                        this.deactivateLoader();
                    }, this));
                }
            },
            /**
             * Completes an internal page transition, triggering the appropriate events after animation is done
             * @param {Deferred} transitionPromise promise that represents the current process we're waiting on
             * @param {{fromPath: String, toPath: String, animId: Number, paused: Boolean, resourcePromise: Deferred}} requestInfo an object that represents the fromPath, toPath, resourcePromise, animId, and paused state
             * @return {Deferred} promise that will resolve when the transition is complete
             * @private
             */
            _finishChangePage: function(transitionPromise, requestInfo) {
                var finishChangePagePromise = $.Deferred();
                transitionPromise.done(_.bind(function(htmlFrag) {
                    if (requestInfo.animId !== this._animId) {
                        return;
                    }
                    this._triggerBeforePageReveal(htmlFrag, requestInfo);
                    var animationPromise = this.animateChangePagePostData(requestInfo.fromPath, requestInfo.toPath, htmlFrag, requestInfo.paused);
                    if (requestInfo.paused) {
                        this.setFixedPosition(StateManager.getBreakingNewsOffset());
                    }
                    if (animationPromise) {
                        animationPromise.done(_.bind(function() {
                            this._triggerAfterPageReveal(requestInfo).done(function() {
                                finishChangePagePromise.resolve();
                            });
                        }, this));
                    } else {
                        this._triggerAfterPageReveal(requestInfo).done(function() {
                            finishChangePagePromise.resolve();
                        });
                    }
                }, this));
                return finishChangePagePromise.promise();
            },
            swapContent: function(fadeOut, fadeIn, immediate) {
                if (this.isSafari5 || this.isApple || immediate) {
                    // safari and apple can't deal with the fade, so we just snap them into place
                    fadeIn.insertAfter(fadeOut);
                    fadeOut.remove();
                    return $.Deferred().resolve();
                } else {
                    var scrollPosition = fadeOut.css('top') || 0;
                    scrollPosition -= App.getScrollPosition();
                    this.$top.scrollTop(0);
                    fadeIn.css({'z-index': 100});
                    fadeOut.css({position: 'absolute', 'z-index': 101, opacity: 1, top: scrollPosition});
                    fadeIn.insertAfter(fadeOut);
                    return this.animate(fadeOut, 'opacity', 0, this.options.animations.fadeIn.duration).always(function() {
                        fadeIn.css({'z-index': ''});
                        fadeOut.remove();
                    });
                }
            },
            pause: function() {
                this.destroyModules(false, true);
            },
            /**
             * Helper function that inserts the html markup on the page for new app reveals
             * Will call afterPageReveal when the reveal animation and request are done.
             * If requestPromise is provided, that means htmlFrag is a temporary loader, and the final
             * content is still coming
             * @param {jQuery} htmlFrag jQuery object representing either the actual content to load or a temporary loader to reveal
             * @param {{fromPath: String, toPath: String, animId: Number, paused: Boolean, resourcePromise: Deferred}} requestInfo an object that represents the fromPath, toPath, resourcePromise, animId, and paused state
             * @param {Deferred} revealCompleteDeferred this is the deferred that indicates when the entire reveal is done
             * @param {Deferred} [requestPromise] promise for the ajax request if one is still in progress
             * @private
             */
            _revealAppMarkup: function(htmlFrag, requestInfo, revealCompleteDeferred, requestPromise) {
                if (requestInfo.animId !== this._animId){
                    return;
                }
                if (!requestPromise) {
                    this._triggerBeforePageReveal(htmlFrag, requestInfo);
                }
                this._insertAppMarkup(htmlFrag, requestInfo.paused);
                var animationPromise = this.animateRevealApp(requestInfo.fromPath, requestInfo.toPath, requestInfo.paused);
                TrafficCop.addAnimation(animationPromise);
                animationPromise.done(_.bind(function() {
                    if (!requestPromise) {
                        // we just animated in the real content, fire the post events
                        this._triggerAfterPageReveal(requestInfo).done(function(){
                            revealCompleteDeferred.resolve();
                        });
                    } else {
                        // we're still waiting on a request to finish
                        // this means we've loaded a temporary loader and need to swap the loader with real content
                        requestPromise.done(_.bind(function(htmlFrag) {
                            if (requestInfo.animId !== this._animId) {
                                return;
                            }
                            this._triggerBeforePageReveal(htmlFrag, requestInfo);
                            var promise = this.swapContent(this.$el, htmlFrag, requestInfo.paused);
                            this.setElement(htmlFrag, false);
                            promise.done(_.bind(function(){
                                this._triggerAfterPageReveal(requestInfo).done(function() {
                                    revealCompleteDeferred.resolve();
                                });
                            }, this));
                        }, this));
                    }
                }, this));
            },
            /**
             * This waits for the resource promise to be completed and calls the afterPageReveal event with the
             * correct ViewClass. This also delegates Events if the fromPath is not null
             * @param {{fromPath: String, toPath: String, animId: Number, paused: Boolean, resourcePromise: Deferred}} requestInfo an object that represents the fromPath, toPath, resourcePromise, animId, and paused state
             * @return {Deferred} jquery promise object
             * @private
             */
            _triggerAfterPageReveal: function(requestInfo) {
                this.appRevealed = true;
                return $.Deferred(_.bind(function(defer){
                    requestInfo.resourcePromise.done(_.bind(function(ViewClass) {
                        if (requestInfo.animId !== this._animId) {
                            return;
                        }
                        try {
                            if (!requestInfo.paused && requestInfo.fromPath !== null) {
                                this.delegateEvents();
                            }
                            this._getPageInfo(requestInfo.fromPath, requestInfo.toPath, requestInfo.paused, this.$el);
                            this.afterPageReveal(requestInfo.fromPath, requestInfo.toPath, requestInfo.paused, ViewClass);
                            if (!requestInfo.paused) {
                                AdManager.requestAds(this.pageInfo, this.getClientAdInfo());
                            }
                        } catch (ex) {
                            console.error('View threw an exception on afterPageReveal event: ', (ex.stack || ex.stacktrace || ex.message));
                        }
                        defer.resolve();
                    }, this));
                }, this)).promise();
            },
            /**
             * Fires callback to beforePageReveal
             * @param {jQuery} htmlFrag object with the html fragment we're rendering
             * @param {{fromPath: String, toPath: String, animId: Number, paused: Boolean, resourcePromise: Deferred}} requestInfo an object that represents the fromPath, toPath, resourcePromise, animId, and paused state
             * @private
             */
            _triggerBeforePageReveal: function(htmlFrag, requestInfo) {
                if (htmlFrag) {
                    try {
                        this.beforePageReveal(requestInfo.fromPath, requestInfo.toPath, htmlFrag, requestInfo.paused);
                    } catch (ex) {
                        console.error('View threw an exception on beforePageReveal event: ', (ex.stack || ex.stacktrace || ex.message));
                    }
                } else {
                    // initial page load, no request
                    try {
                        this.beforePageReveal(requestInfo.fromPath, requestInfo.toPath, this.$el, requestInfo.paused);
                    } catch (ex) {
                        console.error('View threw an exception on beforePageReveal event: ', (ex.stack || ex.stacktrace || ex.message));
                    }
                }
            },
            /**
             * Internal function for getting the pageInfo for the current url and setting the title correctly
             * @param {String} fromPath path we're coming from
             * @param {String} toPath path we're going to
             * @param {Boolean} paused specifying if the web load is a preload or not
             * @param {jQuery} htmlFrag object with the html fragment we're rendering
             * @private
             */
            _getPageInfo: function(fromPath, toPath, paused, htmlFrag){
                // reset the old pageInfo object
                // this is set to broken so if setPage fails, we have a record of it being bad
                this.pageInfo = {};
                try{
                    this.setPage(fromPath, toPath, paused, htmlFrag);
                }catch(ex){
                    console.error('View threw an exception on setPage event: ', (ex.stack || ex.stacktrace || ex.message));
                }
                if (!paused) {
                    if('None' === (this.pageInfo.seotitletag || 'None')) {
                        document.title = 'USATODAY.com';
                    } else {
                        document.title = this.pageInfo.seotitletag;
                    }
                }
            },
            /**
             * This is a function that will decide how to animate the removal of this app
             * @param {String} fromPath path of where we're transitioning from
             * @param {String} toPath path of the view we're going to
             * @return {Deferred} promise object that will resolve when removal is complete
             */
            removeApp: function(fromPath, toPath){
                var removalPromise = $.Deferred();
                try{
                    this._animId++;
                    this.beforeAppRemove(fromPath, toPath);
                    this.destroyModules(false);
                    // defer the animation, to give the dom time to settle down
                    _.defer(_.bind(function(){
                        this._triggerAnimateRemoveApp(fromPath, toPath, removalPromise);
                    }, this));
                }catch(ex){
                    console.error('View threw an exception trying to removeApp: ', (ex.stack || ex.stacktrace || ex.message));
                    removalPromise.resolve();
                }
                removalPromise.always(_.bind(function(){
                    try{
                        this.afterAppRemove(fromPath, toPath);
                    }catch(ex){
                        console.error('View threw an exception on afterAppRemove event: ', (ex.stack || ex.stacktrace || ex.message));
                    }
                    this._safeDestroy();
                }, this));
                return removalPromise.promise();
            },
            _triggerAnimateRemoveApp: function(fromPath, toPath, removalPromise){
                try{
                    var animationPromise = this.animateRemoveApp(fromPath, toPath);
                    TrafficCop.addAnimation(animationPromise).always(function(){
                        removalPromise.resolve();
                    });
                }catch(ex){
                    console.error('View threw an exception on animateRemoveApp: ', (ex.stack || ex.stacktrace || ex.message));
                    removalPromise.resolve();
                }
            },
            /**
             * Destroys the current app, and removes the markup, will never throw an exception
             * @private
             */
            _safeDestroy: function(){
                try{
                    this.destroy(true);
                }catch(ex){
                    console.error('View threw an exception on destroy: ', (ex.stack || ex.stacktrace || ex.message));
                    this.$el.remove();
                }
            },

            /**************************************************************
             * Action functions (animation, fixed positioning)
             **************************************************************/

            /**
             * Overridable function that can change how the current app animates in
             * @param {String} fromPath path we're animating from
             * @param {String} toPath path we're animating to
             * @param {Boolean} paused specifying if the web load is a preload or not
             * @return {Deferred} jQuery promise object that will resolve when reveal animation is complete
             */
            animateRevealApp: function(fromPath, toPath, paused){
                if (this.isApple && paused){
                    return $.Deferred().resolve();
                }else{
                    return this.show(true);
                }
            },

            /**
             * Overridable function that can change how the current view animates out
             * @param {String} fromPath path we're animating from
             * @param {String} toPath path we're animating to
             * @return {Deferred} Promise object that will resolve when removal animation is complete
             */
            animateRemoveApp: function(fromPath, toPath){
                return this.hide(true);
            },

            /**
             * animates page to page within an app
             * @param {String} fromPath path we're leaving
             * @param {String} toPath path we're about to go to
             * @return {Deferred} a promise object that resolves when the animation is complete
             */
            animateChangePagePreData: function(fromPath, toPath){
                // no op, defaults to no animation
            },

            /**
             * Overridable, Given html fragment, animates it into place
             * @param {String} fromPath
             * @param {String} toPath
             * @param {jQuery} htmlFrag
             * @param {Boolean} paused
             * @return {Deferred} promise object that will resolve when the animation is done
             */
            animateChangePagePostData: function(fromPath, toPath, htmlFrag, paused){
                var promise = this.swapContent(this.$el, htmlFrag, paused);
                this.setElement(htmlFrag, false);
                return promise;
            },
            /**
             * Sets the app into a fixed position so an overlay can be placed on top of it
             * @param {Number} offset current scroll position
             * @param {Boolean} partialCover specifies whether the overlay is fully covering this view
             */
            setFixedPosition: function(offset, partialCover){
                if (!partialCover && (this.isSafari5 || this.isApple)){
                    this.$el.hide();
                } else {
                    this.$el.css({position: 'fixed', 'top': offset});
                }
            },
            /**
             * Clears the fixed positioning of app
             */
            clearFixedPosition: function(){
                if (this.isSafari5 || this.isApple){
                    this.$el.show();
                }else{
                    this.$el.css({position: '', 'top': ''});
                }
            },
            /**
             * Triggers a generic app level loader
             */
            activateLoader: function() {
            },
            /**
             * Turns off a generic app level loader
             */
            deactivateLoader: function() {
            },

            /**************************************************************
             * Event Callbacks
             **************************************************************/

            /**
             * Gets called before the transition and removal of the current app.
             * This only gets called when the current transition will trigger a removal of this app
             * @param {String} fromPath path we're leaving
             * @param {String} toPath path we're about to go to
             */
            beforeAppRemove: function(fromPath, toPath){
                //no op
            },
            /**
             * Gets called after the transition and before the removal/destruction of the current app.
             * @param fromPath path we're leaving
             * @param toPath path we're about to go to
             */
            afterAppRemove: function(fromPath, toPath){
                //no op
            },
            /**
             * Called before new content is animated in or revealed.
             * This can be called when this view is created, or when transitioning within the view
             * @param {String} fromPath path we're leaving
             * @param {String} toPath path we're about to go to
             * @param {jQuery} htmlFrag that's about to be placed on the page
             * @param {Boolean} paused variable specifying if the view should load up in a paused state
             */
            beforePageReveal: function(fromPath, toPath, htmlFrag, paused){
                //no op
            },
            /**
             * Called after new content has been successfully animated in or revealed.
             * This can be called when this view is created, or when transitioning within the view
             * @param {String} fromPath path we're leaving
             * @param {String} toPath path we're about to go to
             * @param {Boolean} paused variable specifying if the view should load up in a paused state
             * @param {Object} [PageClass] optional view class, requested by overriding getPageRequirements()
             */
            afterPageReveal: function(fromPath, toPath, paused, PageClass){
                if (PageClass){
                    this.subviews.page = new PageClass({
                        el: this.$el
                    });
                }
            },
            /**
             * Gets the html for a temporary app reveal loader
             * @param {String} toPath path we're going to
             */
            getRevealAppLoader: function(toPath){

            },
            /**
             * Called when an overlay is about to be removed (closed) on top of this app. Added
             * @param {String} toPath param so that the section nav could be updated properly when overlay is 
             * closed.
             */
            beforeOverlayRemove: function(toPath){

            },
            /**
             * Called when an overlay has finished animating in (opening) over this app
             * @param {Number} offset Scroll offset top of this view
             */
            afterOverlayReveal: function(offset){

            },
            /**
             * Gets custom client side information from the current app
             */
            getClientAdInfo: function() {

            },
            /**
             * Overridable analytics callback on new page requests. This gets called immediately after beforePageReveal event
             * @param {String} fromPath path we're leaving
             * @param {String} toPath path we're about to go to
             * @param {Boolean} paused variable specifying if the load is not the active view
             * @param htmlFrag either the html frag that's about to be rendered, or this.$el
             */
            setPage: function(fromPath, toPath, paused, htmlFrag){
                // stash the pageInfo object in case it changes before we are allowed to fire page:load
                var pageInfo = this.pageInfo = $.parseJSON(htmlFrag.find('.pageinfo.data').text()) || {};
                if (!this.pageInfo.templatetype){
                    this.pageInfo.templatetype = htmlFrag.attr('data-template') || '';
                }
                if (!this.pageInfo.url){
                    this.pageInfo.url = App.getPageUrl();
                }
                if (!paused) {
                    _.defer(function() {
                        TrafficCop.getAnimationCompletion().done(function(){
                            // don't fire this until all animations are complete
                            PubSub.trigger('page:load', pageInfo);
                        });
                    });
                }
            }
        });
        return BaseAppView;
    }
);

/**
 * @fileoverview Simple Extendable Overlay.
 * @author Jay Merrifield
 */
define('simpleoverlay',[
    'jquery', 
    'underscore', 
    'backbone', 
    'baseappview', 
    'state', 
    'app', 
    'pubsub'
],
function(
    $, 
    _, 
    Backbone, 
    BaseAppView, 
    StateManager, 
    App, 
    PubSub
) {


        /**
         * View class.
         */
        var SimpleOverlay = BaseAppView.extend({
            // View element.
            el: '#overlay',

            // general overlay events.
            originalEvents: {
                'click .transition-wrap': 'close',
                'click .close-overlay': 'close'
            },
            // overridable events
            additionalEvents: {

            },

            events: function() {
                return _.extend({}, this.originalEvents, this.additionalEvents);
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed during init.
             */
            initialize: function(options) {
                options = $.extend(true, {
                    template: '<div id="overlay" class="no-transition">' +
                                '<div class="content">' +
                                    '<div class="transition-wrap">' +
                                        '<article class="asset clearfix story ui-loading light-medium">' +
                                    '</article></div>' +
                                '</div>' +
                                '<div class="film show"></div>' +
                              '</div>'
                }, options);
                this.preloadUrl = options.preloadedUrl || '';
                this.win = App.get('win');
                this.scrollEl = App.get('scrollEl');

                _.bindAll(this, 'close');

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            beforeAppRemove: function(fromPath, toPath){
                this.positionCloseButton('absolute', App.getScrollPosition());
            },

            getRevealAppLoader: function(toPath){
                var htmlFrag = $(this.options.template),
                    winHeight = this.win.height() - 40,
                    stagedTransitionWrap = htmlFrag.find('.transition-wrap');
                this.prepareContentForTransition(stagedTransitionWrap, 0, winHeight);
                return htmlFrag;
            },

            animateChangePagePreData: function(fromPath, toPath) {
                var winHeight = this.win.height() - 40,
                    scrollPosition = App.getScrollPosition(),
                    activeTransitionWrap = this.$('.transition-wrap:last');
                this.prepareContentForTransition(activeTransitionWrap, scrollPosition, winHeight);

                var htmlFrag = $(this.options.template);
                var stagedTransitionWrap = htmlFrag.find('.transition-wrap');
                this.prepareContentForTransition(stagedTransitionWrap, 0, winHeight);

                this.collection.append(stagedTransitionWrap);

                this.scrollEl.scrollTop(0);

                // Unfix close button so it can slide with card.
                this.positionCloseButton('absolute', scrollPosition, activeTransitionWrap);

                return this.swapContent(activeTransitionWrap, stagedTransitionWrap);
            },

            prepareContentForTransition: function(transitionWrap, scrollPosition, winHeight){
                transitionWrap.css({height:winHeight});
                transitionWrap.children().css({'top': -1 * scrollPosition});
            },

            animateChangePagePostData: function(fromPath, toPath, htmlFrag, paused) {
                var transition = htmlFrag.find('.transition-wrap');
                transition.css('height', this.win.height() - 40);
                return this.swapContent(this.$('.transition-wrap'), transition).done(_.bind(function(){
                    transition.css('height', '');
                }, this));
            },

            afterPageReveal: function(fromPath, toPath, paused, ViewClass){
                if (fromPath === null){
                    StateManager.preloadPath(this.preloadUrl);
                }
                this.collection = this.$('.content');
                this.positionCloseButton('fixed');

                if (ViewClass){
                    this.subviews.view = new ViewClass({
                        el: this.$('.transition-wrap:first'),
                        path: toPath
                    });
                }
            },

            /**
             * This function sets the close button to either fixed or absolute positioning.
             * @param {String} positionType Either 'fixed' or 'absolute'.
             * @param {Number} [scrollPosition] position of where the close button should be placed, defaults to 0
             * @param {jQuery} [closeStoryWrap] The story wrap parent of the close button to position, defaults to this.$('.close-wrap').
             */
            positionCloseButton: function(positionType, scrollPosition, closeStoryWrap) {
                var closeWrap = closeStoryWrap ? closeStoryWrap.find('.close-wrap') : this.$('.close-wrap');
                if (positionType === 'absolute') {
                    closeWrap.css({ 'position': positionType, 'top': scrollPosition || 0 });
                } else {
                    closeWrap.css({ 'position': positionType, 'top': '' });
                }
            },

            /**
             * Close page.
             * @param {Event} e Click event to close overlay.
             */
            close: function(e) {
                if (e && e.target !== e.currentTarget){
                    // trap clicks inside the transition wrap to prevent them from closing the overlay
                    return;
                }
                var utvalue = $(e.currentTarget).attr("data-ht") || 'modalclose';
                PubSub.trigger('heattrack', utvalue);
                StateManager.navigateToPreloadedUrl();
                if (e) return false;
            }

        });


        /**
         * Return view class.
         */
        return SimpleOverlay;
    }
);

/**
 * @fileoverview Global footer module view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 * @author kris.hedstrom@f-i.com (Kris Hedstrom)
 */
define('views/modules/footer',['jquery', 'underscore', 'backbone', 'easing', 'pubsub', 'app'],
    function($, _, Backbone, Easing, PubSub, App) {


        /**
         * View class.
         */
        var FooterView = Backbone.View.extend({

            // View element.
            el: '.footer',

            // Events.
            events: {
                'click p.site-index': 'toggle',
                'click .footer-more-trigger': 'showMore'
            },

            /**
             * Initialize class view.
             */
            initialize: function() {
                // Cache selectors.
                this.$scrollEl = App.get('scrollEl');
                this.$nav = $('nav', this.$el);
                this.$doc = App.get('doc');
                this.$win = App.get('win');
                this.$toggle = $('p.site-index');

                // @TODO: make this dynamic
                // Height of expanded nav + bottom margin of cards + height of
                // collapsed footer.
                this.footerHeight = 383;
            },

            /**
             * Show more footer items when clicking 'more...'
             */
            showMore: function(e) {
                e.preventDefault();
                var moreLink = $(e.currentTarget);
                moreLink.hide().siblings('.footer-more-item').show();
            },

            /**
             * Subscribe to multiple events at once.
             * @param {Object} events Key/value pair of events to subscribe to.
             */
            subscribers: function(events) {
                var evt;
                for(evt in events) {
                    this.subscribe(evt, events[evt]);
                }
            },

            /**
             * Subscribe to event
             * @param {String} evt Name of event.
             * @param {String} callback Name of callback function to call.
             */
            subscribe: function(evt, callback) {
                if(typeof this[callback] === 'function') {
                    PubSub.on(evt, $.proxy(function() {
                        this[callback].apply(this, arguments);
                    }, this));
                }
            },

            /**
             * Show/hide toggle for footer.
             * @param {Event} e Browser event triggering toggle.
             */
            toggle: function(e) {
                if(e) {e.preventDefault();}
                var scrollTop = this.$el.offset().top -
                    $('#nav').height() - $('#breaking').height();
                this.$toggle.toggleClass('open');
                this.$scrollEl.animate(
                    {'scrollTop': scrollTop},
                    500,
                    'easeInOutCubic');
                this.$nav.slideToggle(500, 'easeInOutCubic');
            },

            /**
             * Collapse / close the footer.
             */
            close: function() {
                this.$nav.hide();
                this.$toggle.removeClass('open');
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {Boolean} removeEl Option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.undelegateEvents();
                if (removeEl) {this.remove();}
            }
        });


        /**
         * Return view class.
         */
        return FooterView;
    }
);

/**
 * @fileoverview ContactUs Overlay.
 * @author Jay Merrifield
 */
define('views/pages/static-overlay',['jquery', 'underscore', 'backbone', 'state', 'app', 'simpleoverlay', 'views/modules/footer'],
    function($, _, Backbone, StateManager, App, SimpleOverlay, Footer) {
        var StaticOverlayView = SimpleOverlay.extend({
            additionalEvents: {
                'click .static-page-faq a': 'expandFaq'
            },

            initialize: function(options) {
                // call base class initialize
                SimpleOverlay.prototype.initialize.call(this, options);
            },

            afterPageReveal: function(fromPath, toPath, paused){
                this.subviews.footer = new Footer();
                SimpleOverlay.prototype.afterPageReveal.apply(this, arguments);
            },

            expandFaq: function(e){
                var $link = $(e.target);
                var $answer = $link.next();
                if ($answer.is(':visible')){
                    $link.parent().removeClass('active');
                    $answer.slideUp(200);
                }else{
                    $link.parent().addClass('active');
                    $answer.slideDown(200);
                }
            }
        });
        return StaticOverlayView;
    }
);
/**
 * @fileoverview 404 / 500 view.
 * @author Robert Huhn
 */
define('views/pages/404',['jquery', 'underscore', 'backbone', 'baseappview', 'state',
    'pubsub',
    'views/pages/static-overlay'
],
function($, _, Backbone, BaseAppView, StateManager, PubSub, StaticOverlay) {

    /**
     * View class.
     */
    var ErrorView = StaticOverlay.extend({

        initialize: function(options) {
            // call base class initialize
            StaticOverlay.prototype.initialize.call(this, options);

            if (this.options.ajax){
                // we're not a state managed object
                this.render(this.options.htmlFrag);
                StateManager.registerFullScreenView(this);
                this.afterPageReveal();
            }
        },

        afterPageReveal: function(fromPath, toPath, paused){
            StaticOverlay.prototype.afterPageReveal.apply(this, arguments);
        },

        /**
         * Close overlay.
         */
        close: function(e) {
            if (e && e.target !== e.currentTarget){
                // trap clicks inside the transition wrap to prevent them from closing the overlay
                return;
            }
            if (this.options.ajax){
                StateManager.clearFullScreenView(this);
                this.destroy(true);
            }else{
                StateManager.navigateToPreloadedUrl();
            }
            return false;
        }
    });
    return ErrorView;

});

/**
 * Library to handle calls to/from Facebook for various service interactions.
 */
define('facebook',[
    'jquery',
    'underscore',
    'pubsub',
    'fwinfo',
    'app',
    'state'
],
function(
    $,
    _,
    PubSub,
    FwInfo,
    App,
    StateManager
)
    {
        var _config = site_config.AUTH.FACEBOOK,
            _appid  = _config.APPID,
            _channelUrl = _config.CHANNELURL,
            _authResponse,
            _user = {},
            _perms = _config.PERMISSIONS,
            _wasServiceCalled = false,
            _facebookPromise;

        var $body = App.get("body");

        function facebookAuthResponseChange(response) {
            Facebook.getFB(function() {
                if (response.status === "connected" && response.authResponse)
                    facebookLogin(response.authResponse);
                else {
                    facebookLogout(response.authResponse);
                    PubSub.trigger('FB:UnAuth');
                }
            });
        }

        function facebookHeaderUpdate() {
            var photo = _user.photoSmall || '';
            var name = _user.name || '';
            Facebook.getFB(function() {
                $('.fb-avatar').attr({
                    src: photo,
                    height: 22,
                    width: 22
                });
                $('.fb-display-name').text(name);
            });
        }

        function facebookCheckLoginStatus() {
            PubSub.off('page:load', facebookCheckLoginStatus);
            Facebook.getFB(function() {
                FB.getLoginStatus(function(response) { facebookAuthResponseChange(response); }, true);
            });
        }

        PubSub.on('auth.authResponseChange', facebookAuthResponseChange);
        PubSub.on('auth:user', facebookHeaderUpdate);
        PubSub.on('page:load', facebookCheckLoginStatus);

        function requireFB() {
            if (!_facebookPromise){
                _facebookPromise = $.Deferred(function(defer){
                    StateManager.fetchData('//connect.facebook.net/en_US/all.js',
                        {
                            cache: true,
                            data: {},
                            dataType: 'script'
                        }).done(function() {
                            FB.init({
                                appId      : _appid,
                                channelUrl : _channelUrl,
                                status     : true,  // facebook will check if logged in
                                cookie     : true,  // yes we want to use cookies
                                xfbml      : false  // don't auto parse xfbml tags
                            });

                            FB.Event.subscribe('auth.authResponseChange', function(response) {
                                _authResponse= response;
                                PubSub.trigger('auth.authResponseChange', response);
                            });
                            defer.resolveWith(Facebook, [FB]);
                        });
                }).promise();
            }
            return _facebookPromise;
        }

        function facebookLogout() {
            // DOM manip
            Facebook.getFB(function() {
                _authResponse = undefined;
                _user = {};
                FwInfo.setsessionvalue("uniqueid","");

                if($body.hasClass('fbauth')) $body.removeClass('fbauth');
                facebookHeaderUpdate();
            });
        }

        function facebookLogin(authResponse) {
            Facebook.getFB(function() {

                _authResponse = authResponse;

                // DOM manip
                $body.addClass('fbauth');

                //Query the FB photo from the FB API
                FB.api({
                        method: 'fql.query',
                        query: 'SELECT name, pic_square FROM user WHERE uid= '+authResponse.userID
                    }, function(apiResponse) {
                        _user.name = apiResponse[0].name;
                        _user.photoSmall = apiResponse[0].pic_square;
                        PubSub.trigger('auth:user', apiResponse[0]);
                    });
                if (!_wasServiceCalled) {
                    StateManager.fetchData('/facebook/tokens/' + authResponse.accessToken, {
                            type: 'POST',
                            data: {
                                accessExpires: authResponse.expiresIn,
                                accessToken: authResponse.accessToken,
                                userID: authResponse.userID
                            }
                        }).done(function(r){
                            FwInfo.setsessionvalue("uniqueid", r.success.UserUniqueId);
                        });

                    _wasServiceCalled = true;
                }

                //if user is logging in on the User Auth Page, redirect him or her back to content
                if(document.location.pathname.toLowerCase() === '/userauth/default/') {
                    console.log("user auth'd! about to go back!");
                    history.back();
                }
            });
        }

        var Facebook = {
            /**
             *  Get Facebook
             *  @param {Function} doneCallback callback function
             *  Registers the callback and then when the require block has returned resolve all promises
             *  Facebook.getFB(function(    ) { ... });
             */
            getFB: function(doneCallback) {
                return requireFB().done(doneCallback);
            },

            init: function() {},

            login: function(cb) {
                this.getFB(function() {
                    FB.login(cb, { scope : _perms } );
                });
            },

            logout: function() {
                this.getFB(function() {
                    FwInfo.setsessionvalue("uniqueid","");
                    PubSub.trigger('FB:loggedout');
                    //IT HELPS TO ACTUALLY LOG THE USER OUT OF FACEBOOK TOO, YA KNOW?  ADDED THE ACTUAL FB.LOGOUT CALL BACK IN
                    FB.logout(function(response) {
                      // user is now logged out
                    });
                });
            },

            parse: function() {
                this.getFB(function() {
                    FB.XFBML.parse();
                });
            },
            permissions: function() {
                return _perms;
            },
            status: function() {
                if(!_authResponse) {
                    return _authResponse.status;
                } else {
                    return false;
                }
            }
        };

        return Facebook;
    }
);


/**
 * Library to handle calls to/from Googleplus for various service interactions.
 */
/*global gapi:true*/
define('googleplus',[
    'jquery',
    'underscore',
    'pubsub',
    'fwinfo',
    'app' 
],
function(
    $,
    _,
    PubSub,
    FwInfo,
    App
)
    {
        var _defer = $.Deferred(), 
             _turnOnGP= (site_config.AUTH.GOOGLEPLUS.TURNON)||false, 
             _clientid = site_config.AUTH.GOOGLEPLUS.CLIENTID,
             _apppackagename = site_config.AUTH.GOOGLEPLUS.APPPACKAGENAME,
             _plusonejslib = site_config.AUTH.GOOGLEPLUS.JSLIBURL,
             _cookiepolicy = site_config.AUTH.GOOGLEPLUS.COOKIEPOLICY||'none',
             _didGPLoaded = false,
             _scope ='https://www.googleapis.com/auth/plus.login',
             _requestvisibleactions= 'http://schemas.google.com/AddActivity', 
             _onetimeloadcheck = false,
             _userclick = false, 
             gpbtn= $('.gp-login-btn')
             ;

        
        if (_turnOnGP){
           _onetimeloadcheck= true; 
           if(gpbtn.hasClass('hidden')) gpbtn.removeClass('hidden');
        }

         
        function requireGP(){
            require([_plusonejslib], function() {
                _defer.resolve(gapi);   
            });
        }


        function loadGoogleplus(){   
            if (!_onetimeloadcheck) {
                PubSub.trigger('UA:RemoveGPFBlink');
                return;
            };

            Googleplus.getGP(function(){

                if (!_didGPLoaded) {
                    _didGPLoaded = true;
                    window.signinCallback= Googleplus.processAuth;
                    Googleplus.rendersignin();
                    PubSub.trigger('UA:RemoveGPFBlink');
                }
            });

        }

        var Googleplus = {
            rendersignin:function(){
                if (gapi && gapi.signin) {
                    gapi.signin.render('gp-login-btn-ph',{"clientid":  _clientid,
                        "requestvisibleactions": _requestvisibleactions,
                        "scope":_scope,
                        "immediate":'false',
                        "apppackagename":_apppackagename,
                        "cookiepolicy":_cookiepolicy,
                        "callback": this.processAuth});
                }
            },

            logout:function(){ 
                FwInfo.setsessionvalue('gpuserstatus','loggedout');
                PubSub.trigger('UA:logout');

            },
             /**
             *  Get GooglePlus
             *  @param {Function} donecallback callback function
             *  Registers the callback and then when the require block has returned resolve all promises
             *  Googleplus.getGP(function(    ) { ... });
             */
            getGP: function(donecallback) {
                 _defer.then(donecallback);
                requireGP(); 
                return _defer.promise();
            },

            loadgp:function(ondemand){ 
                if(typeof ondemand !== 'undefined' && ondemand)
                    _userclick =true;
                loadGoogleplus();
            },

            processAuth:function(authResult) {
                if (authResult.error==='immediate_failed') return;
                if(!_userclick && FwInfo.getsessionvalue('gpuserstatus')==='loggedout') return;
                gapi.auth.setToken(authResult); 
                gapi.client.load('plus', 'v1', function() { 
                    var request = gapi.client.plus.people.get({
                        'userId': 'me'
                      });
                    request.execute(Googleplus.googlePlusHeaderUpdate);

                 });  
            },

            googlePlusHeaderUpdate: function(resp){
                //For P1 we are still using FB class 
                FwInfo.setsessionvalue('gpuserstatus','loggedin'); 
                PubSub.trigger('UA:UpdateAvatar',{imgurl:resp.image.url,displayname:resp.displayName});
                
            }

            
        };

        return Googleplus;
    }
)
;
/**
 * Library to handle calls to/from user auth servicefor various service interactions.
 */
define('userauth',[
    'jquery',
    'underscore',
    'pubsub', 
    'app',
    'googleplus',
    'facebook'
],
function(
    $,
    _,
    PubSub, 
    App,
    GooglePlus,
    Facebook
)
    {
        var $body = App.get("body"),
            _fblogoutbtn = $('.fb-logout-btn'),
            _gplogoutbtn = $('.gp-logout-btn');

        // Set event listener for FB -> GP dependency 
        //ON FB logout or unath call GP
        PubSub.on('FB:UnAuth', GooglePlus.loadgp); 
        PubSub.on('FB:loggedout',GooglePlus.logout);  
        PubSub.on('UA:UpdateAvatar',updateavatar);
        PubSub.on('UA:logout',loguserout);
        PubSub.on('UA:RemoveGPFBlink',turnoffFBevent);
        PubSub.on('auth:user', makeSureGoogleIsHidden);

        function turnoffFBevent(){
            PubSub.off('FB:UnAuth', GooglePlus.loadgp);
        }
        function updateavatar(resp){
            UserAuth.updateAvatar(resp);
        }

        function loguserout(){
            UserAuth.logUserOut();
        }

        function makeSureGoogleIsHidden() {
            if(_fblogoutbtn.hasClass('hidden')) { _fblogoutbtn.removeClass('hidden'); }
            if(!_gplogoutbtn.hasClass('hidden')) { _gplogoutbtn.addClass('hidden'); }
        }

        var UserAuth = { 

            updateAvatar: function(resp) {
                //as of now its only GP, FB to follow later
                if(!$body.hasClass('fbauth')) {  
                    $body.addClass('fbauth');
                    $('.fb-avatar').attr({
                        src: resp.imgurl,
                        height: 22,
                        width: 22
                    });
                    $('.fb-display-name').text(resp.displayname); 
                    if(_gplogoutbtn.hasClass('hidden')) _gplogoutbtn.removeClass('hidden');
                    if(!_fblogoutbtn.hasClass('hidden')) _fblogoutbtn.addClass('hidden');
                }
            },
            //Currently this method is called only for the Googleplus 
            logUserOut: function(){
                if($body.hasClass('fbauth')) $body.removeClass('fbauth');
                if(!_gplogoutbtn.hasClass('hidden')) _gplogoutbtn.addClass('hidden');
                if(_fblogoutbtn.hasClass('hidden')) _fblogoutbtn.removeClass('hidden');
            },

            onClickLogin: function(provider){
                //as of now its only GP 
                if(provider==='googleplus')
                    GooglePlus.loadgp(true);
            },

            onClickLogout: function(provider){
                //as of now its only GP 
                if(provider==='googleplus')
                    GooglePlus.logout();
            } 
            
        };

        return UserAuth;
    }
)
;
/**
 * @fileoverview Input Fields on forms.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/input-field',[
    'jquery',
    'underscore',
    'baseview'
],
    function(
        $,
        _,
        BaseView
        ) {
        
        var InputField = BaseView.extend({

            events: {
                'focus':'onInputFocus',
                'blur':'onInputBlur',
                'keydown':'onKeydown'
            },

            initialize: function(options) {

                options = $.extend({
                    errorSelector: '.ui-form-field-error',
                    onShowError: null
                }, options);

                BaseView.prototype.initialize.call(this, options);
                _.bindAll(this,'onClearButtonClick');

                // we are checking whether this $el is an input tag, if not, we are assuming it is a textarea tag
                this.isInputField = (this.$el.prop("tagName") || '').toLowerCase() === 'input' ? true : false;
                this.hasPlaceHolderNativeSupport = Modernizr.input.placeholder ? true : false;
                this.placeholder = this.$el.attr('placeholder');

                if (this.placeholder) {
                    this.showPlaceHolder();
                }

                if (this.$el.data('clearable')) {
                    this._setupClearButton();
                }

                if (this.$el.attr('required')) {
                    this._setupErrorDiv();
                }

                // input field is required,
                    // check for error div

            },

            showPlaceHolder: function(){
                if (!this.hasPlaceHolderNativeSupport) {
                    this.setInputValue(this.placeholder);
                    this.$el.addClass('ui-text-input-placeholder');
                }
            },

            clearPlaceHolder: function(){
                if (!this.hasPlaceHolderNativeSupport) {
                    this.clearInputValue();
                    this.$el.removeClass('ui-text-input-placeholder');
                }
            },

            getInputValue: function(){
                if (this.isInputField) {
                    return this.$el.val();
                } else {
                    return this.$el.text();
                }
            },

            clearInputValue: function(){
                if (this.isInputField) {
                    this.$el.val('');
                } else {
                    this.$el.text('');
                }
            },

            setInputValue: function(value){
                if (this.isInputField) {
                    this.$el.val(value);
                } else {
                    this.$el.text(value);
                }
            },

            /**
             * Sets up clear button.
             */
            _setupClearButton: function(){
                this.clearButton = $('<div class="ui-text-input-clear-btn" style="display:none"></div>');
                this.$el.parent().append(this.clearButton);
                this.clearButton.on('mousedown.' + this.cid, _.bind(function(e){
                    this.onClearButtonClick(e);
                }, this));
            },

            /**
             * Handles focus events on an input field.
             */
            onInputFocus: function(e) {
                var inputValue = this.getInputValue();
                if (inputValue !== '') {
                    if (inputValue === this.placeholder) {
                        this.clearPlaceHolder();
                    } else {
                        if (this.clearButton) {
                            this.clearButton.show();
                        }
                    }

                }
            },

            /**
             * Handles blur events on an input field.
             * @param {Event} e blur event
             */
            onInputBlur: function(e) {
                if (this.getInputValue() === '') {
                    this.resetInput();
                }
                if (this.clearButton){
                    this.clearButton.hide();
                }
            },

            /**
             * Resets input field
             */
            resetInput: function() {
                if (this.placeholder) {
                    this.showPlaceHolder();
                } else {
                    this.clearInputValue();
                }
                if (this.clearButton) {
                    this.clearButton.hide();
                }

            },

            /**
             * Handler for typing.
             * @param {Event} e keyup event
             */
            onKeydown: function(e) {
                // we need to produce a slight delay to get the item pressed via the input field
                clearTimeout(this.keyPressDelay);
                this.keyPressDelay = setTimeout(_.bind(function() {
                    if (this.clearButton) {
                        if (this.getInputValue() === '' || this.getInputValue() === this.placeholder) {
                            this.clearButton.hide();
                        } else {
                            this.clearButton.show();
                        }
                    }
                },this), 1);
            },

            /**
             * Handler for clicking the clear icon
             */
            onClearButtonClick: function(e) {
                e.preventDefault();
                this.clearInputValue();
                this.clearButton.hide();
                this.$el.focus();
            },

            showError: function(message){
                if (this.options.errorSelector) {
                    this.$el.closest(this.options.errorSelector);
                }
                if (this.options.onShowError) {
                    this.options.onShowError();
                }
            },

            destroy: function(removeEl){
                if (this.clearButton) {
                    this.clearButton.off('.' + this.cid);
                    this.clearButton.remove();
                }
                this.clearInputValue();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return InputField;
    }
);
/**
 * @fileoverview Autocomplete module.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/autocomplete',[
    'jquery',
    'underscore',
    'baseview',
    'pubsub',
    'state',
    'views/modules/form/input-field'
],
    function(
        $,
        _,
        BaseView,
        PubSub,
        StateManager,
        InputField
        ) {
        
        var AutoComplete = BaseView.extend({

            events: {
                "keydown .ui-text-input": 'onKeyDown',
                "paste .ui-text-input": 'updateResults',
                "focusout" : 'onInputBlur',
                "mousedown .ui-autocomplete-result-item": 'onMouseDownResultItem',
                "mouseenter .ui-autocomplete-result-item": 'onResultMouseEnterLeave',
                "mousedown .ui-text-input-clear-btn": 'onClearButtonClick'
            },

            initialize: function(options) {
                options = $.extend({
                    url: this.$el.data('autocomplete-url') || '',
                    ajaxOptions: null,
                    resultDisplayTemplate: null,
                    resultValueTemplate: null,
                    onError: null,
                    onSelect: null,
                    maxResults: 4,
                    onShowResults: null
                }, options);

                this.inputField = this.$el;

                // must reassign this.el to input field's container to allow backbone events to access its contents
                this.setElement(this.$el.parent(),false);

                this.autoCompleteResultsContainer = $('<ul class="ui-autocomplete-result-container"></ul>');
                this.autoCompleteContent = $('<div class="ui-autocomplete-content"></div>');
                this.autoCompleteContent.append(this.autoCompleteResultsContainer);
                this.$el.append(this.autoCompleteContent);

                _.bindAll(this, 'updateResults','showResult','clearResults');
                BaseView.prototype.initialize.call(this,options);

                // checks if supplied url is an underscore template
                var isUrlTemplate = this.options.url.indexOf("<%=") !== -1; // true
                if (isUrlTemplate) {
                    // url contains an underscore template!
                    this.fetchUrl = function(value) {
                        return _.template(this.options.url, {'query':value});
                    };
                } else {
                    this.fetchUrl = function(value) {
                        return this.options.url+value;
                    };
                }

                this.subviews.inputField = new InputField({
                    el: this.inputField
                });
            },

            updateResults: function(){
                // we need to produce a slight delay to get the item pressed via the input field
                clearTimeout(this.keyPressDelay);
                this.keyPressDelay = setTimeout(_.bind(function() {
                    var inputValue = this.inputField.val();
                    if (inputValue.length) {
                        // cancel call to fetchdata if currently running
                        if (this.fetcher) {
                            this.fetcher.abort();
                        }
                        this.fetcher = this._fetchResults(inputValue);
                    } else {
                        this.clearResults();
                    }
                },this), 1);
            },

            /**
             * When a autocomplete match is hovered with the mouse.
             */
            onResultMouseEnterLeave : function(e){
                var el = $(e.target);
                if (!el.hasClass('hover')) {
                    // remove all hover class from all other results
                    this.autoCompleteResultsContainer.find('.ui-autocomplete-result-item').removeClass('hover');
                    el.addClass('hover');
                }
            },

            /**
             * When focus on autocomplete input field is lost.
             */
            onInputBlur : function(){
                this.clearResults();
                if (this.fetcher) {
                    this.fetcher.abort();
                }
            },

            /**
             * When clicking a result with the mouse.
             * @param e
             */
            onMouseDownResultItem: function(e){
                if (e.which === 3) {
                    // don't count right clicks as valid
                    return;
                }
                this.selectItem($(e.currentTarget));
            },

            /**
             * Handler for typing.
             * @param {Event} e Event
             */
            onKeyDown: function(e) {
                var keycode = (e.keyCode ? e.keyCode : e.which),
                    items = this.autoCompleteResultsContainer.find('.ui-autocomplete-result-item'),
                    hoveredItem = items.filter('.ui-autocomplete-result-hover');
                if (keycode === 9){
                    // tab key
                    return;
                } else if ((keycode === 38 || keycode === 40)) {
                    // up/down arrow keys
                    e.preventDefault();
                    if (items.length) {
                        this.onResultItemUpDownArrowKeyPress(keycode, hoveredItem);
                    }
                } else if (keycode === 13){
                    // enter key
                    if (hoveredItem.length) {
                        e.preventDefault();
                        this.selectItem(hoveredItem);
                    } else {
                        this.clearResults();
                    }
                } else if (keycode === 32 && hoveredItem.length) {
                    // spacebar
                    this.selectItem(hoveredItem);
                } else {
                    this.updateResults();
                }

            },

            /**
             * When user presses the up or down arrow keys when typing in the input field.
             * @param {Number} keycode Keycode
             * @param {Jquery} currHoveredItem Item that is currently hovered over.
             */
            onResultItemUpDownArrowKeyPress: function(keycode, currHoveredItem){
                var items = this.autoCompleteResultsContainer.find('.ui-autocomplete-result-item');
                items.removeClass('ui-autocomplete-result-hover');
                if (keycode === 38) {
                    // up
                    if (!currHoveredItem.length || this.inputField.val() === this.currentInputFieldValue) {
                        this.hoverResultItem(items.last());
                    } else if (currHoveredItem.prev().length) {
                        this.hoverResultItem(currHoveredItem.prev());
                    } else {
                        this.inputField.val(this.currentInputFieldValue);
                    }
                } else {
                    // down
                    if (!currHoveredItem.length) {
                        this.hoverResultItem(items.first());
                    } else if (currHoveredItem && currHoveredItem.next().length) {
                        this.hoverResultItem(currHoveredItem.next());
                    } else {
                        this.inputField.val(this.currentInputFieldValue);
                    }
                }
            },

            /**
             * Hovers an autocomplete result element.
             * @param element Element to be hovered.
             */
            hoverResultItem: function(element){
                element.addClass('ui-autocomplete-result-hover');
                this.inputField.val(element.text());
            },

            /**
             * Processes selected autocomplete items.
             * @param {jQuery} element The selected element
             */
            selectItem: function(element){
                var value = element.data('value') || element.text();
                this.inputField.val(value);
                if (this.options.onSelect) {
                    this.options.onSelect(value, element.data('result'));
                }
                this.clearResults();
            },

            resetInput: function(){
                this.clearResults();
                this.subviews.inputField.resetInput();
            },

            /**
             * Displays an autocomplete result by appending it to appropriate DOM element
             * @param {String} displayValue
             * @param {String} dataValue
             * @param {Object} dataItem
             */
            showResult: function(displayValue, dataValue, dataItem){
                var itemEl = $('<li class="ui-autocomplete-result-item"></li>');
                itemEl.text(displayValue);
                itemEl.data('value', dataValue);
                if (dataItem) {
                    itemEl.data('result', dataItem);
                }
                this.autoCompleteResultsContainer.append(itemEl);

            },

            /**
             * Clears out autocomplete results.
             */
            clearResults: function(){
                this.autoCompleteResultsContainer.empty();
            },

            /**
             * Handler for clicking the clear icon
             * @param {Event} e click event
             */
            onClearButtonClick: function(e) {
                this.clearResults();
            },

            /**
             * Display results.
             * @param {String} value String value to check
             */
            _fetchResults: function(value){
                StateManager.fetchData(this.fetchUrl(value), this.options.ajaxOptions)
                    .done(_.bind(function(data){
                        // empty previous results
                        this.autoCompleteResultsContainer.empty();
                        //truncate data set to max amount
                        data = data.slice(0, this.options.maxResults);
                        if (this.options.onShowResults) {
                            this.options.onShowResults(data, this.autoCompleteResultsContainer, this.inputField);
                        }
                        this._parseResults(data);
                        this.currentInputFieldValue = this.inputField.val();
                    },this))
                    .fail(_.bind(function(msg){
                        if (this.options.onError) {
                            this.options.onError(msg);
                        }
                    },this));
            },

            /**
             * Parse result data.
             * @param {Object} data Data set.
             */
            _parseResults: function(data) {
                $.map(data, _.bind(function (item) {
                    var resultDataValue,
                        resultDisplayValue;
                    if (this.options.resultDisplayTemplate) {
                        resultDisplayValue = _.template(this.options.resultDisplayTemplate, item);
                    }
                    if (this.options.resultValueTemplate) {
                        resultDataValue =  _.template(this.options.resultValueTemplate, item);
                    }
                    this.showResult(resultDisplayValue, resultDataValue, item);
                }, this));
            },

            destroy: function(removeEl){
                this.autoCompleteContent.remove();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return AutoComplete;
    }
);
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.6
 * 
 * Requires: 1.2.2+
 */
(function(a){function d(b){var c=b||window.event,d=[].slice.call(arguments,1),e=0,f=!0,g=0,h=0;return b=a.event.fix(c),b.type="mousewheel",c.wheelDelta&&(e=c.wheelDelta/90),c.detail&&(e=-c.detail/3),h=e,c.axis!==undefined&&c.axis===c.HORIZONTAL_AXIS&&(h=0,g=-1*e),c.wheelDeltaY!==undefined&&(h=c.wheelDeltaY/90),c.wheelDeltaX!==undefined&&(g=-1*c.wheelDeltaX/90),d.unshift(b,e,g,h),(a.event.dispatch||a.event.handle).apply(this,d)}var b=["DOMMouseScroll","mousewheel"];if(a.event.fixHooks)for(var c=b.length;c;)a.event.fixHooks[b[--c]]=a.event.mouseHooks;a.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=b.length;a;)this.addEventListener(b[--a],d,!1);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=b.length;a;)this.removeEventListener(b[--a],d,!1);else this.onmousewheel=null}},a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery)
;
define("mousewheel", function(){});

/**
 * @fileoverview BaseScroll view module.
 *
 * Defines methods that are shared by both the vertical
 * and horizontal scroll components
 *
 * TROUBLESHOOTING:
 * The most common reason for the scroller not working is the divs for the
 * container and scrollable content not being setup correctly. Please ensure
 * that the container is passed as the el (and not as a Jquery object) and
 * the content resides within the container and either has the
 * 'scrollable-content' class on it, or you pass through a new contentClass
 * within your options.
 *
 * If you are still having issues console.log the height and contentHeight
 * (or width / contentWidth) variables in the refresh method and ensure they
 * are as you would expect them to be. The key is to ensure that the content
 * doesn't shrink to be the same width/height as it's container. The
 * contentHeight should be larger than the height for a scroll bar to be
 * required.
 *
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
 define('views/modules/scroller/base-scroll',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app',
    'mousewheel'
],
function(
    $,
    _,
    Backbone,
    BaseView,
    PubSub,
    App
)
    {

        /**
         * View class.
         */
        var BaseScrollView = BaseView.extend({

            // Events.
            events: {
                'mousewheel': 'handleMouseWheel',
                'mouseenter': 'onMouseEnter',
                'mouseleave': 'onMouseLeave',
                'touchstart': 'onTouchStart',
                'mousedown .scrolldragger': 'onDraggerMouseDown',
                'mouseenter .scrolldragger': 'onDraggerMouseOver',
                'mouseleave .scrolldragger': 'onDraggerMouseOut',
                'mousedown .scrollbar': 'onBarClick'
            },

            removeActiveDelay: 300,

            /**
             * Initialize view.
             */
            initialize: function(options) {
                options = $.extend({
                    disabled: false,
                    contentClass: '.scrollable-content',
                    lockPageScroll: true,
                    delayScroll: false,
                    minDraggerSize: 40
                }, options);

                _.bindAll(this,
                    'onDraggerMouseUp',
                    'onDraggerMouseMove',
                    'onTouchMove',
                    'onTouchStop',
                    'setMouseInHouse',
                    'clearMouseInHouse'
                );

                this.content = this.$(options.contentClass);
                this.bar = $(options.template).hide();
                this.bar.addClass('scrollbar');
                this.dragger = this.bar.find('.scrolldragger');
                this.body = App.get('body');
                this.$el.append(this.bar);

                //vars
                this.isMouseDown = false;
                this.isMouseOver = false;
                this.draggerOffset = 0;

                BaseView.prototype.initialize.call(this, options);

                this.refresh();
            },

            /**
             * Bind events.
             */
            bindEvents: function() {
                this.delegateEvents();
            },

            /**
             * Unbind events.
             */
            unbindEvents: function() {
                this.undelegateEvents();
                // clear any drag/etc handlers we put on the body that might still be in effect
                this.body.off('.' + this.cid);
                clearInterval(this.accelerationTimer);
                clearTimeout(this.enterDelay);
                clearTimeout(this.leaveDelay);
            },

            /**
             * Refresh / setup the scrollbar
             */
            refresh: function() {
                this.content = this.$(this.options.contentClass);
                if(this.options.disabled || this.content.length === 0) {
                    //there is no content for the scroller return and do nothing
                    return;
                }

                this.viewportSize = this.getViewportSize();
                this.contentSize = this.getContentSize();
                this.contentViewportRatio = this.viewportSize / this.contentSize;

                if(this.contentViewportRatio < 1) {
                    var draggerSize = this._calculateDraggerSize(this.viewportSize, this.contentViewportRatio, this.contentSize);
                    this.draggerSize = this._setDraggerSize(draggerSize);
                    if (!this.active){
                        this.bar.show();
                        this.bindEvents();
                        this.active = true;
                    }
                    // must call after this.active = true
                    this.shiftContent(0, 0);
                } else {
                    if (this.active){
                        this.bar.hide();
                        this.unbindEvents();
                        this.active = false;
                    }
                }
            },
            _calculateDraggerSize: function(viewportSize, contentViewportRatio, contentSize){
                var draggerSize = Math.round(viewportSize * contentViewportRatio);
                if (draggerSize < this.options.minDraggerSize){
                    // recalculate viewport to content ratio given the max position of both
                    var maxContentPosition = contentSize - viewportSize;
                    var maxViewportPosition = viewportSize - this.options.minDraggerSize;
                    this.contentViewportRatio = maxViewportPosition / maxContentPosition;
                    // set minimum dragger size
                    draggerSize = this.options.minDraggerSize;
                }
                return draggerSize;
            },

            /**
             * Touch Events!
             */
            onTouchStart: function(event){
                var touches = event.originalEvent.touches;
                if (touches.length > 1 || this.options.disabled){
                    return;
                }
                clearInterval(this.accelerationTimer);
                this.touchX = touches[0].pageX;
                this.touchY = touches[0].pageY;
                this.touchVectorX = 0;
                this.touchVectorY = 0;
                this.touchDragStarted = false;
                this.touchLastMove = (new Date()).getTime();
                this.body.on('touchend.' + this.cid, this.onTouchStop);
                this.body.on('touchcancel.' + this.cid, this.onTouchStop);
                this.body.on('touchmove.' + this.cid, this.onTouchMove);
            },

            onTouchStop: function(event){
                if (event.originalEvent.touches.length !== 0){
                    return;
                }
                this.body.off('.' + this.cid);
                if (this.touchDragStarted){
                    var currentTime = (new Date()).getTime();
                    var timeDelta = currentTime - this.touchLastMove;
                    event.preventDefault();
                    // time between last move and now is soon enough that it should trigger momentum scrolling
                    if (timeDelta < 100){
                        this._triggerScrollingDecelerate(this.touchVectorX, this.touchVectorY, 1500);
                    }
                    return false;
                }
            },

            _triggerScrollingDecelerate: function(initialVectorX, initialVectorY, decelerationTime){
                var startTime = (new Date()).getTime();
                var finalTime = startTime + decelerationTime;
                var touchLastMove = startTime;
                this.accelerationTimer = setInterval(_.bind(function(){
                    var currentTime = (new Date()).getTime();
                    var timeDelta = currentTime - touchLastMove;
                    touchLastMove = currentTime;

                    if (currentTime > finalTime){
                        clearInterval(this.accelerationTimer);
                        return;
                    }
                    currentTime -= startTime;
                    var currentVelocityX = this._adjustVelocityVector(initialVectorX, currentTime, decelerationTime);
                    var currentVelocityY = this._adjustVelocityVector(initialVectorY, currentTime, decelerationTime);
                    this.shiftContent(currentVelocityX * timeDelta, currentVelocityY * timeDelta);
                }, this), 20);
            },

            _adjustVelocityVector: function(initialVector, currentTime, stopTime){
                return initialVector * Math.pow(1 - (currentTime / stopTime), 3);
            },

            onTouchMove: function(event){
                if (event.originalEvent.touches.length !== 1){
                    return;
                }
                var touches = event.originalEvent.touches;
                var deltaX = (touches[0].pageX - this.touchX);
                var deltaY = (touches[0].pageY - this.touchY);
                if (this.touchDragStarted || Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10){
                    // must travel at least 2 pixels to start drags
                    var currentTime = (new Date()).getTime();
                    this.touchDragStarted = true;
                    this.touchX = touches[0].pageX;
                    // vector is in pixels per ms
                    this.touchVectorX = deltaX / (currentTime - this.touchLastMove);
                    this.touchY = touches[0].pageY;
                    // vector is in pixels per ms
                    this.touchVectorY = deltaY / (currentTime - this.touchLastMove);
                    this.touchLastMove = (new Date()).getTime();
                    if (this.shiftContent(deltaX, deltaY) === false){
                        event.preventDefault();
                    }
                }
            },

            onBarClick: function(e) {
                if (e.which !== 1 || e.isDefaultPrevented()){
                    return;
                }
                e.preventDefault();
                var barOffset = this.bar.offset(),
                    mouseX = e.pageX - barOffset.left - this.draggerSize / 2,
                    mouseY = e.pageY - barOffset.top - this.draggerSize / 2;

                //position center of dragger to where the bar was clicked
                this.moveDraggerToPosition(mouseX, mouseY);
                this.onDraggerMouseOver(e);
                this.onDraggerMouseDown(e);
            },

            /**
             * Mouse down.
             */
            onDraggerMouseDown: function(e) {
                if (e.which !== 1){
                    return;
                }
                this.isMouseDown = true;
                e.preventDefault();
                // prevent user text selection while moving the dragger
                this.body.on('mousemove.' + this.cid, this.onDraggerMouseMove);
                this.body.on('mouseup.' + this.cid, this.onDraggerMouseUp);

                //calculate the offset from where the dragger was clicked
                var draggerOffset = this.dragger.offset();
                this.draggerClickOffset = {
                    left: e.pageX - draggerOffset.left,
                    top: e.pageY - draggerOffset.top
                };
            },

            /**
             * Mouse up.
             */
            onDraggerMouseUp: function(e) {
                if (e.which !== 1){
                    return;
                }
                e.preventDefault();
                this.isMouseDown = false;
                this.body.off('.' + this.cid);
                if(!this.isMouseOver) {
                    // if we're still over the dragger, don't remove the hover
                    this.dragger.removeClass('hover');
                }
            },

            onDraggerMouseMove: function(event){
                if(!this.isMouseDown){
                    return;
                }

                var offset = this.bar.offset();
                var barMouseX = event.pageX - offset.left - this.draggerClickOffset.left,
                    barMouseY = event.pageY - offset.top - this.draggerClickOffset.top;

                this.moveDraggerToPosition(barMouseX, barMouseY);
            },

            /**
             * Mouse over.
             */
            onDraggerMouseOver: function(event) {
                this.isMouseOver = true;
                this.dragger.addClass('hover');
            },

            /**
             * Mouse out.
             */
            onDraggerMouseOut: function(event) {
                this.isMouseOver = false;
                if(!this.isMouseDown) {
                    this.dragger.removeClass('hover');
                }
            },

            /**
             * So what's happening below if you when you are scrolling down
             * a page and you go over an area with a scrollbar attached to it.
             * What this does is delay the ability to scroll that sub scroll
             * for 0.3 seconds. This prevents the page from locking when you
             * just intend to scroll over a sub scroll area quickly, instead
             * of locking the page up until you scroll to the end. It can be
             * switched off by setting delayScroll to false in this.options.
             */

            /**
             * Mouse enter.
             */
            onMouseEnter: function(e) {
                clearTimeout(this.leaveDelay);
                this.enterDelay = setTimeout(this.setMouseInHouse, 300);
            },

            /**
             * Mouse leave.
             */
            onMouseLeave: function(e) {
                clearTimeout(this.enterDelay);
                this.leaveDelay = setTimeout(this.clearMouseInHouse, 300);
            },

            setMouseInHouse: function(){
                this.isMouseInTheHouse = true;
            },

            clearMouseInHouse: function(){
                this.isMouseInTheHouse = false;
            },


            handleMouseWheel: function(event, delta, deltaX, deltaY){
                if(this.isMouseDown || (this.options.delayScroll && !this.isMouseInTheHouse)){
                    return;
                }

                deltaY = deltaY * 20;
                deltaX = -1 * deltaX * 20 || deltaY;

                if (this.shiftContent(deltaX, deltaY) === false){
                    event.preventDefault();
                }
            },

            /**
             * Shifting content by certain number of pixels
             */
            shiftContent: function(deltaX, deltaY) {
                var contentPosition = this.content.position(),
                    contentParent = this.content.parent(),
                    contentX = contentPosition.left + deltaX - (parseInt(contentParent.css('padding-left'), 10) || 0) - (parseInt(contentParent.css('margin-left'), 10) || 0),
                    contentY = contentPosition.top + deltaY - (parseInt(contentParent.css('padding-top'), 10) || 0) - (parseInt(contentParent.css('margin-top'), 10) || 0);

                if (this.moveContentToPosition(contentX, contentY)){
                    // move succeeded, stop bubbling
                    return false;
                }else{
                    // if we tried to move the content and it didn't move as much as we wanted
                    // it means we hit the end of the content, should we block the event from bubbling?
                    if (this.options.lockPageScroll){
                        return false;
                    }
                }
            },

            destroy: function() {
                this.unbindEvents();
                this.bar.remove();
                BaseView.prototype.destroy.apply(this, arguments);
            },

            /*********************************************************
             * Abstract functions, required implementing by subclasses
             *********************************************************/

            moveDraggerToPosition: function(locationX, locationY){

            },

            moveContentToPosition: function(locationX, locationY){

            },

            /**
             * will scroll to make the element visible
             * @param {jQuery} item html element that we want to be visible
             * @param {Boolean} pageJump specifies if we're moving the viewport a full page, or just one line
             * @param {Number} duration time for animation
             * @param {String} [easing] easing formula
             */
            scrollToElement: function(item, pageJump, duration, easing) {

            },

            animateContentToPosition: function(locationX, locationY, duration, easing){

            },

            getViewportSize: function(){
                return 0;
            },

            getContentSize: function(){
                return 0;
            },

            _setDraggerSize: function(draggerSize){
                return draggerSize;
            }

        });


        /**
         * Return view class.
         */
        return BaseScrollView;
    }
);

/**
 * @fileoverview VerticalScroll view module.
 *
 * When instantiating the class pass and object that defines:
 * el: The container of the scrollable content and where the scrollbar will be placed
 * contentClass: The class name that the scrollable content div has (this class must sit
 * within the container)
 * template: markup for the actual scroller
 * padding: left/right padding amount for the scroller
 * To use outside gallery thumbs set an alternate el and contentClass when instantiating
 * the class. Any issues / questions don't hesitate to contact me.
 *
 * SEE BASE-SCROLL.JS FOR TROUBLESHOOTING ADVICE
 *
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
 define('views/modules/scroller/vertical-scroll',[
    'jquery',
    'underscore',
    'app',
    'views/modules/scroller/base-scroll'
],
function(
    $,
    _,
    App,
    BaseScroll
)
    {

        /**
         * View class.
         */
        var VerticalScrollView = BaseScroll.extend({

            /**
             * Initialize view.
             */
            initialize: function(options) {

                options = $.extend({
                    color: 'light', // light or dark
                    fadeout: false,
                    draggerPaddingTop: 3, // how much padding should we give around the dragger
                    draggerPaddingBottom: 3
                }, options);

                var fade = (this.options.fadeout) ? 'fadeout' : '';

                // Set up html template based on color.
                var compiled = _.template('<div class="vertical-scroll ui-<%= color %> <%= fade %>"><div class="scrolldragger"><div class="over-icon"></div></div></div>');
                options.template = compiled({color: options.color, fade: fade});

                // Remove any pre-existing instances just in case.
                this.$('.vertical-scroll').remove();

                BaseScroll.prototype.initialize.call(this, options);
            },
            getViewportSize: function(){
                return this.$el.height();
            },
            getContentSize: function(){
                return this.content.height();
            },
            _setDraggerSize: function(draggerSize){
                draggerSize -= (this.options.draggerPaddingTop + this.options.draggerPaddingBottom);
                this.dragger.css({height: draggerSize});
                return draggerSize;
            },

            animateContentToPosition: function(locationX, locationY, duration, easing){
                var minPosition = this.viewportSize - this.contentSize,
                    actualLocationY = Math.max(minPosition, Math.min(locationY, 0));
                easing = easing || 'ease-out';
                $.when(this.animate(this.dragger, 'top', (-1 * actualLocationY * this.contentViewportRatio) + 'px', duration || 0, easing),
                        this.animate(this.content, 'top', actualLocationY + 'px', duration, easing))
                    .done(_.bind(function(){
                        this.$el.trigger('scrollBarUpdate', [actualLocationY / minPosition]);
                    }, this));
            },

            /**
             * will scroll to make the element visible
             * @param {jQuery} item html element that we want to be visible
             * @param {Boolean} pageJump specifies if we're moving the viewport a full page, or just one line
             * @param {Number} duration time for animation
             * @param {String} [easing] easing formula
             */
            scrollToElement: function(item, pageJump, duration, easing) {
                var shift, itemHeight = item.outerHeight(),
                    itemTopPosition = item.position().top + item.parent().position().top,
                    itemBottomPosition = itemTopPosition + itemHeight;
                if (itemTopPosition < 0) {
                    var viewportSize = this.getViewportSize();
                    if (pageJump) {
                        shift = itemTopPosition + (itemHeight - viewportSize);
                    } else {
                        shift = itemTopPosition;
                    }
                } else if (itemBottomPosition > this.getViewportSize()) {
                    if (pageJump) {
                        shift = itemTopPosition;
                    } else {
                        shift = itemTopPosition + (itemHeight - this.getViewportSize());
                    }
                }
                if (shift) {
                    var finalPosition = this.content.position().top - shift;
                    this.animateContentToPosition(0, finalPosition, duration, easing);
                }
            },

            moveContentToPosition: function(locationX, locationY){
                if (!this.active){
                    return false;
                }
                var minPosition = this.viewportSize - this.contentSize,
                    actualLocationY = Math.max(minPosition, Math.min(locationY, 0));
                this._positionDragger(-1 * actualLocationY * this.contentViewportRatio);
                this._positionContent(actualLocationY);
                this.$el.trigger('scrollBarUpdate', [actualLocationY / minPosition]);
                return actualLocationY === locationY;
            },
            moveDraggerToPosition: function(locationX, locationY){
                if (!this.active){
                    return false;
                }
                var maxPosition = this.viewportSize - (this.draggerSize + this.options.draggerPaddingBottom + this.options.draggerPaddingTop),
                    actualLocationY = Math.max(0, Math.min(locationY, maxPosition));
                this._positionDragger(actualLocationY);
                this._positionContent(-1 * actualLocationY / this.contentViewportRatio);
                this.$el.trigger('scrollBarUpdate', actualLocationY / maxPosition);
                return actualLocationY === locationY;
            },
            _positionDragger: function(y){
                y += this.options.draggerPaddingTop;
                y = Math.round(y);
                if (this.useCSSTransforms){
                    this.dragger.css({top: '0'});
                    this.dragger[0].style[this.transformCssName] = 'translate(0,' + y + 'px)';
                }else{
                    this.dragger.css({top: y});
                }
            },
            _positionContent: function(y){
                y = Math.round(y);
                if (this.useCSSTransforms){
                    this.content.css({top: '0'});
                    this.content[0].style[this.transformCssName] = 'translate(0,' + y + 'px)';
                }else{
                    this.content.css({top: y});
                }
            }
        });


        /**
         * Return view class.
         */
        return VerticalScrollView;
    }
);

/**
 * @fileoverview Dropdown module
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 * Used for adding dropdown functionality to html elements (preferably divs or ul's) that have a 'ui-dropdown' class.
 * For dropdowns that are <select></select>'s, the SelectDropdown class (select-dropdown.js) should be used instead.
 */

define('views/modules/form/dropdown',[
    'jquery',
    'underscore',
    'app',
    'baseview',
    'state',
    'views/modules/scroller/vertical-scroll'
],
    function(
        $,
        _,
        App,
        BaseView,
        StateManager,
        VerticalScroll
        ) {
        
        var Dropdown = BaseView.extend({

            events: {
                'click .ui-dropdown-value': 'onClick',
                'keydown': 'onKeyDown',
                'click .ui-dropdown-item': 'onItemClick',
                'hover .ui-dropdown-item': 'onItemHover',
                'click .ui-dropdown-item-link': 'onItemLinkClick'
            },

            initialize: function(options) {
                options = $.extend({
                    onSelect: null, // callback function when item is selected ie. function(selectedItem){}
                    dropdownContentSelector: '.ui-dropdown-content',
                    itemsContainerSelector: '.ui-dropdown-items-container',
                    highlightedItemClass: 'ui-dropdown-item-highlight'
                }, options);

                _.bindAll(this, 'refresh');
                BaseView.prototype.initialize.call(this, options);

                this.body = App.get('body');

                if (!this.$el.attr('tabindex')) {
                    // set default tab index to 0 if none provided
                    this.$el.attr('tabindex', 0);
                }

                // cache frequently used items
                this.dropdownItems = this.$('.ui-dropdown-item');

                this.refresh();

            },
            /**
             * open dropdown contents.
             */
            open: function(){
                var dropdownValue = this.getValue(),
                    matchingContentItem = this.dropdownItems.filter('[data-value="' + dropdownValue + '"]');
                if (matchingContentItem.length === 1) {
                    matchingContentItem.attr('data-selected','selected');
                } else {
                    matchingContentItem = this.dropdownItems.eq(0).addClass(this.options.highlightedItemClass);
                }
                this.$el.addClass('expanded');
                this.isDropdownOpen = true;
                if (!this.subviews.scrollbar) {
                    this.subviews.scrollbar = new VerticalScroll({
                        el: this.$(this.options.dropdownContentSelector),
                        contentClass: this.options.itemsContainerSelector,
                        padding: 6
                    });
                } else {
                    this.subviews.scrollbar.refresh();
                }
                this.subviews.scrollbar.scrollToElement(matchingContentItem, false, 50);

                // add click event to body to close dropdown when user clicks anywhere outside of it
                this.body.on('click.'+ this.cid, _.bind(function(e){
                    // This is testing if the clicked item's parents contain this.el (the dropdown)
                    // When it does not, we know this event was triggered outside of the dropdown
                    // and therefore, can safely close dropdown
                    if($(e.target).closest(this.el).length === 0) {
                        this.close();
                    }
                },this));
            },

            /**
             * close dropdown contents.
             */
            close: function(){
                this.$el.removeClass('expanded');
                this.dropdownItems.removeClass(this.options.highlightedItemClass);
                this.isDropdownOpen = false;
                this.body.off('click.' + this.cid);
            },

            /**
             * When dropdown is clicked
             * @param {Event} e Hover event.
             */
            onClick: function(e) {
                if (!this.isDropdownOpen){
                    this.open();
                } else {
                    this.close();
                }
            },

            /**
             * When pressing keys (while dropdown is in focus).
             * @param {Event} e Keypress event
             */
            onKeyDown: function(e) {
                var keycode = (e.keyCode ? e.keyCode : e.which);
                // up/down key
                if (keycode === 38 || keycode === 40) {
                    if (!this.isDropdownOpen) {
                        this.open();
                    } else {
                        this.onResultItemUpDownArrowKeyPress(keycode);
                    }
                    e.preventDefault();
                    return;
                } else if (keycode === 27) {
                    // escape key
                    if (this.isDropdownOpen) {
                        e.preventDefault();
                        this.close();
                    }
                } else if (keycode === 9) {
                    // tab key
                    if (this.isDropdownOpen) {
                        e.preventDefault();
                        this.close();
                    }
                } else if (keycode === 32 || keycode === 13) {
                    // space bar/enter key
                    this.onSpaceBarEnterKeyPress();
                    e.preventDefault();
                    return;
                }
            },

            /**
             * When user presses the up or down arrow keys when typing in the input field.
             * @param {Number} keycode Up or down keycode
             */
            onResultItemUpDownArrowKeyPress: function(keycode){
                var highlightedItemClass = this.options.highlightedItemClass,
                    highlightedItem = this.dropdownItems.filter('.' + highlightedItemClass);
                this.dropdownItems.removeClass(highlightedItemClass);
                if (!highlightedItem.length){
                    highlightedItem = this.dropdownItems.eq(0);
                    highlightedItem.addClass(highlightedItemClass);
                } else if (keycode === 38){
                    // up
                    var prevItem = highlightedItem.prev();
                    if (!prevItem.length) {
                        // loop!
                        prevItem = this.dropdownItems.last();
                    }
                    prevItem.addClass(highlightedItemClass);
                    if (this.subviews.scrollbar) {
                        this.subviews.scrollbar.scrollToElement(prevItem, false, 50);
                    }
                } else if (keycode === 40) {
                    // down
                    var nextItem = highlightedItem.next();
                    if (!nextItem.length) {
                        // loop!
                        nextItem = this.dropdownItems.first();
                    }
                    nextItem.addClass(highlightedItemClass);
                    if (this.subviews.scrollbar) {
                        this.subviews.scrollbar.scrollToElement(nextItem, false, 50);
                    }
                }
            },

            /**
             * When spacebar is pressed when selecting a dropdown item.
             */
            onSpaceBarEnterKeyPress: function(){
                var selectedItem = this.dropdownItems.filter('.' + this.options.highlightedItemClass),
                    href = selectedItem.find('a').attr('href');
                if (selectedItem.length) {
                    this.setValue(selectedItem.data('value'));
                }
                if (href) {
                    App.triggerRoute(href);
                }
            },

            /**
             * When a dropdown item is clicked.
             * @param {Event} e Event
             */
            onItemClick: function(e){
                this.setValue($(e.currentTarget).data('value'));
            },

            /**
             * When a dropdown a (href) link is clicked.
             * @param {Event} e Event
             */
            onItemLinkClick: function(e){
                this.setValue($(e.currentTarget).closest('.ui-dropdown-item').data('value'));
            },

            /**
             * When a dropdown item is hovered over.
             * @param e Event
             */
            onItemHover: function(e){
                this.dropdownItems.filter('.' + this.options.highlightedItemClass).removeClass(this.options.highlightedItemClass);
                $(e.currentTarget).addClass(this.options.highlightedItemClass);
            },

            /**
             * Updates dropdown value using value string
             * @param {String} dataValue
             */
            setValue: function(dataValue) {
                var dropdownValueDiv = this.$('.ui-dropdown-value'),
                    matchingItem = this.dropdownItems.filter('[data-value="' + dataValue + '"]');
                this.dropdownItems.removeAttr('data-selected');
                dropdownValueDiv.data('value', dataValue);
                dropdownValueDiv.html(matchingItem.text());
                matchingItem.attr('data-selected','selected');
                if (this.options.onSelect){
                    this.options.onSelect(dataValue, matchingItem.text(), matchingItem);
                }
                if (this.isDropdownOpen) {
                    this.close();
                }
            },

            /**
             * Grabs current data-value of dropdown
             * @returns {*}
             */
            getValue: function(){
                var dropdownValueDiv = this.$('.ui-dropdown-value');
                if (dropdownValueDiv.data('value')) {
                    return dropdownValueDiv.data('value');
                } else {
                    return '';
                }
            },

            /**
             * Refreshes/updates dropdown item contents with new data
             * @param {String} html html to append to DOM
             */
            refresh: function(html){
                if (html) {
                    html = $(html);
                    this.$(this.options.itemsContainerSelector).html(html);
                    this.dropdownItems = html;
                }
                // parse initially selected item if there is one
                this.initialSelectedItem = this.dropdownItems.filter('[data-selected="selected"]');
                if (this.initialSelectedItem.length === 1) {
                    this.setValue(this.initialSelectedItem.data('value'));
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             */
            destroy: function(removeEl) {
                this.body.off('.' + this.cid);
                BaseView.prototype.destroy.call(this, removeEl);
            }
        });

        /**
         * Return view class.
         */
        return Dropdown;
    }
);
/**
 * @fileoverview Select Dropdown module
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 * Used for adding dropdown functionality to <select></select> elements ONLY.
 * For dropdowns that are not select elements (i.e. divs or uls), the Dropdown (dropdown.js) should be used instead.
 */

define('views/modules/form/select-dropdown',[
    'jquery',
    'underscore',
    'baseview',
    'views/modules/form/dropdown'
],
    function(
        $,
        _,
        BaseView,
        Dropdown
        ) {
        
        var SelectDropdown = BaseView.extend({

            events: {
                'change': 'onChange'
            },

            initialize: function(options) {
                options = $.extend({
                    onSelect: null,
                    dropdownContentSelector: '.ui-dropdown-content',
                    itemsContainerSelector: '.ui-dropdown-items-container',
                    highlightedItemClass: 'ui-dropdown-item-highlight'
                }, options);

                BaseView.prototype.initialize.call(this, options);
                _.bindAll(this, 'refresh', 'onDivDropdownSelect');

                this.$el.hide();
                this.selectOptionItems = this.$('option');
                if (!this.dropdownDiv) {
                    this.dropdownDiv = this._buildDropdownHtml(this.selectOptionItems);
                }
                // set select dropdown's tabindex to negative number to remove it from the tabbing flow
                this.$el.attr('tabindex','-1');
                this.dropdownDiv.insertAfter(this.$el);

                this.subviews.dropdown = new Dropdown({
                    el: this.dropdownDiv,
                    onSelect: this.onDivDropdownSelect,
                    itemsContainerSelector: this.options.itemsContainerSelector,
                    highlightedItemClass: this.options.highlightedItemClass
                });
            },
            /**
             * Builds div-version of dropdown
             * @param {JQuery} selectOptionItems set of option tags
             * @returns {*|HTMLElement}
             * @private
             */
            _buildDropdownHtml: function(selectOptionItems) {
                var dropdownDiv = $('<div class="' + this.$el.attr('class') + '"></div>');
                var dropdownValueDiv = $('<div class="ui-dropdown-value ui-btn"></div>');
                var dropdownContent = $('<div class="ui-dropdown-content"></div>');
                var dropdownItemHtml = this._buildDropdownHtmlItems(selectOptionItems);

                // reassign attrs from the select onto the dropdown
                dropdownDiv.attr('class',this.$el.attr('class'));
                dropdownDiv.attr('tabindex', this.$el.attr('tabindex') || 0);

                dropdownDiv.append(dropdownValueDiv).append(dropdownContent);
                dropdownContent.html(dropdownItemHtml);
                return dropdownDiv;
            },

            /**
             * Builds div-version of dropdown items
             * @param {JQuery} selectOptionItems set of option tags
             * @returns {*}
             * @private
             */
            _buildDropdownHtmlItems: function(selectOptionItems){
                var dropdownItemsContainer;
                if (!this.$('.ui-dropdown-items-container').length) {
                    dropdownItemsContainer = $('<ul class="ui-dropdown-items-container"></ul>');
                }
                selectOptionItems.each(_.bind(function(index, el){
                    var item = $(el),
                        selectValue = item.val(),
                        displayValue = item.html(),
                        dropdownItem = $('<li class="ui-dropdown-item" data-value="'+selectValue+'">' + displayValue + '</li>');
                    if (item.is(':selected')){
                        dropdownItem.attr('data-selected','selected');
                    }
                    dropdownItemsContainer.append(dropdownItem);
                }, this));
                return dropdownItemsContainer;
            },

            /**
             * Populates select dropdown with new data
             * @param {String} html String of select <option>'s to populate dropdown with
             */
            refresh: function(html) {
                var dropdownItemContainer = this._buildDropdownHtmlItems($(html));
                this.subviews.dropdown.refresh(dropdownItemContainer.html());
                this.$el.html(html);
            },
            /**
             * When an item from the div-version of dropdown is selected
             * @param {String} dataValue data-value attr of selected item
             * @param {String} displayValue display value of selected item
             * @param {JQuery} selectedItem the selected item
             */
            onDivDropdownSelect: function(dataValue, displayValue, selectedItem){
                this.$el.val(dataValue);
                if (this.options.onSelect) {
                    this.options.onSelect(dataValue, displayValue, selectedItem);
                }
            },

            onChange: function(){
                this.subviews.dropdown.setValue(this.$el.val());

            },

            destroy: function(removeEl) {
                this.dropdownDiv.remove();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return SelectDropdown;
    }
);
/**
 * @fileoverview Toggler module.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/button-toggle',[
    'jquery',
    'underscore',
    'baseview'
],
    function(
        $,
        _,
        BaseView
        ) {
        
        var ButtonToggle = BaseView.extend({

            initialize: function(options) {
                options = $.extend({
                    onSelect: null
                }, options);
                BaseView.prototype.initialize.call(this, options);

                this.toggleItems = this.$el.find('.ui-button-toggle-item');
                this.toggleItems.on('click.' + this.cid, _.bind(function(e){
                    this.onClick($(e.currentTarget));
                }, this));

            },

            /**
             * When a toggle item is clicked
             * @param {JQuery} clickedItem
             */
            onClick: function(clickedItem) {
                if (!clickedItem.hasClass('active')){
                    this.toggleItems.removeClass('active');
                    clickedItem.addClass('active');
                    if (this.options.onSelect) {
                        this.options.onSelect(clickedItem);
                    }
                }
            },

            destroy: function(removeEl) {
                this.toggleItems.off('.' + this.cid);
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return ButtonToggle;
    }
);
/**
 * @fileoverview Toggler module (<select> version).
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/select-button-toggle',[
    'jquery',
    'underscore',
    'baseview',
    'views/modules/form/button-toggle'
],
    function(
        $,
        _,
        BaseView,
        ButtonToggle
        ) {
        
        var SelectButtonToggle = BaseView.extend({

            events: {
                'change': 'updateValue'
            },

            initialize: function(options) {
                options = $.extend({
                    onSelect: null
                }, options);

                BaseView.prototype.initialize.call(this, options);
                _.bindAll(this, 'onDivToggleSelect');

                this.$el.hide();
                if (!this.divToggle) {
                    this.divToggle = this._buildSelectToggle(this.$el);
                }
                this.divToggleItems = this.divToggle.find('.ui-button-toggle-item');

                this.subviews.buttonToggle = new ButtonToggle({
                    el: this.divToggle,
                    onSelect: this.onDivToggleSelect
                });

            },

            /**
             * Creates div-version of the toggle.
             * @param {jQuery} el Select element
             * @private
             */
            _buildSelectToggle: function(el){
                var selectOptions = el.find('option'),
                    toggleEl = $('<ul class="' + el.attr('class') + '"></ul>');
                // add select toggle class to add uniqueness to select-version
                el.addClass('ui-button-toggle-select').removeClass('ui-button-toggle');
                selectOptions.each(_.bind(function(index, el){
                    var item = $(el),
                        selectValue = item.val(),
                        displayValue = item.html(),
                        dropdownItem = $('<li class="' + 'ui-button-toggle-item ui-btn" data-value="'+selectValue+'">'+displayValue+'</li>');
                    if (item.attr('class')) {
                        dropdownItem.addClass(item.attr('class'));
                    }
                    // handle first active value
                    if (item.is(':selected')) {
                        dropdownItem.addClass('active');
                    }
                    toggleEl.append(dropdownItem);
                },this));

                if (el.attr('tabindex')) {
                    toggleEl.attr('tabindex', el.attr('tabindex'));
                }
                toggleEl.insertAfter(el);
                return toggleEl;
            },

            /**
             * When an item from the div-version of toggle is selected
             * @param {JQuery} selectedItem
             */
            onDivToggleSelect: function(selectedItem){
                this.$el.val(selectedItem.data('value'));
                // the 'change' event does not automatically fire when changing select value via js,
                // so we need to create an event just for our divToggle so it can be easily evaluated in our onChange func
                this.divToggleChangeEvent = $.Event('change');
                this.updateValue(this.divToggleChangeEvent);
            },

            /**
             * When the toggle value changes
             */
            updateValue: function(e) {
                var matchingItem = this.divToggleItems.filter('[data-value="' + this.$el.val() + '"]');
                this.divToggleItems.removeAttr('data-selected');
                matchingItem.attr('data-selected','selected');
                if (this.options.onSelect) {
                    this.options.onSelect(matchingItem.data('value'), matchingItem.text(), matchingItem);
                }
                // we only need to update the div-version with the change if
                // if it was not the reason this function was fired
                var isTriggeredByDivToggle = e === this.divToggleChangeEvent ? true : false;
                if (!isTriggeredByDivToggle) {
                    this.subviews.buttonToggle.onClick(matchingItem);

                }

            },

            destroy: function(removeEl){
                this.$el.removeClass('ui-button-toggle-select').addClass('ui-button-toggle');
                this.divToggle.remove();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return SelectButtonToggle;
    }
);
/**
 * @fileoverview Form Checkboxes
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/checkbox',[
    'jquery',
    'underscore',
    'baseview'
],
    function(
        $,
        _,
        BaseView
        ) {
        
        var Checkbox = BaseView.extend({

            events: {
                'click': 'onCheckboxInputClick'
            },

            initialize: function(options) {
                options = $.extend({
                    onClick: null // function(clickedItem, isChecked){};
                }, options);
                BaseView.prototype.initialize.call(this, options);
                _.bindAll(this, 'onCheckboxClick');
                this.checkboxDiv = this._buildDivCheckbox(this.$el);
            },

            /**
             * Builds div-version of checkbox
             * @param {Jquery} inputCheckboxEl The checkbox input element
             * @returns {*|HTMLElement}
             * @private
             */
            _buildDivCheckbox: function(inputCheckboxEl){
                var checkboxDiv = $('<div class="' + inputCheckboxEl.attr('class') + '" data-name="' + inputCheckboxEl.attr('name') + '" data-value="' + inputCheckboxEl.val() + '"></div>'),
                    checkboxInputLabelEl = this.$el.closest('form').find('label[for="' + inputCheckboxEl.attr('id') + '"]');
                if (inputCheckboxEl.is(':checked')) {
                    checkboxDiv.addClass('ui-checkbox-checked');
                }
                if (inputCheckboxEl.is(':disabled')) {
                    checkboxDiv.addClass('ui-checkbox-disabled');
                }
                checkboxDiv.on('keydown.' + this.cid + ' click.' + this.cid, _.bind(function(e){
                    if (e.type === 'keydown') {
                        this.onKeyDown(e);
                    } else {
                        this.onCheckboxClick(e);
                    }
                },this));

                var checkboxInputTabIndex = inputCheckboxEl.attr('tabindex');
                // set tabindex to -1 to ignore radio input when tabbing
                inputCheckboxEl.attr('tabindex', '-1');
                if (checkboxInputTabIndex) {
                    checkboxDiv.attr('tabindex', checkboxInputTabIndex);
                } else {
                    checkboxDiv.attr('tabindex', '0');
                }

                var divCheckboxLabelEl = this._buildDivCheckboxLabel(checkboxInputLabelEl);
                checkboxDiv.append(divCheckboxLabelEl);
                checkboxInputLabelEl.hide();

                checkboxDiv.insertAfter(inputCheckboxEl);
                return checkboxDiv;
            },

            /**
             * Builds div-version of checkbox label
             * @param checkboxInputLabelEl
             * @returns {*|HTMLElement}
             * @private
             */
            _buildDivCheckboxLabel: function(checkboxInputLabelEl){
                var divLabel = $('<span class="ui-checkbox-label"></span>');
                if (checkboxInputLabelEl.length) {
                    // move label text inside of new div label
                    divLabel.text(checkboxInputLabelEl.text());
                } else {
                    // if no label, use radio input value as label
                    divLabel.text(this.$el.val());
                }
                return divLabel;
            },

            onKeyDown: function(e){
                var keycode = (e.keyCode ? e.keyCode : e.which);
                if (keycode === 32 || keycode === 13) {
                    // spacebar or enter key
                    e.preventDefault();
                    this.onCheckboxClick(e);
                }
            },

            /**
             * Check
             */
            check: function(){
                this.checkboxDiv.addClass('ui-checkbox-checked');
                if (this.options.onClick) {
                    this.options.onClick(this.checkboxDiv, true);
                }
            },

            /**
             * Un-check
             */
            unCheck: function(){
                this.checkboxDiv.removeClass('ui-checkbox-checked');
                if (this.options.onClick) {
                    this.options.onClick(this.checkboxDiv, false);
                }
            },

            /**
             * When div-version of checkbox is clicked.
             */
            onCheckboxClick: function(e) {
                if (this.checkboxDiv.hasClass('ui-checkbox-checked')) {
                    this.unCheck();
                    this.$el.prop('checked', false);
                } else {
                    this.check();
                    this.$el.prop('checked', true);
                }
            },

            /**
             * When the input checkbox is clicked.
             */
            onCheckboxInputClick: function(e){
                this.onCheckboxClick(e);
            },

            destroy: function(removeEl) {
                this.checkboxDiv.off('.' + this.cid);
                this.checkboxDiv.remove();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return Checkbox;
    }
);
/**
 * @fileoverview Form radio buttons.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/form/radio-button',[
    'jquery',
    'underscore',
    'baseview'
],
    function(
        $,
        _,
        BaseView
        ) {
        
        var RadioButton = BaseView.extend({

            events: {
                'click' : 'onRadioInputClick'
            },

            initialize: function(options) {
                options = $.extend({
                    onClick: null
                }, options);

                BaseView.prototype.initialize.call(this, options);
                if (!this.radioDiv) {
                    this.radioDiv = this._buildDivRadio(this.$el);
                }

            },

            /**
             * Builds the div-version of the radio button
             * @param {Jquery} inputRadioEl The radio button input element
             * @returns {*|HTMLElement}
             * @private
             */
            _buildDivRadio: function(inputRadioEl){
                var radioDiv = $('<div class="' + inputRadioEl.attr('class') + '" data-name="' + inputRadioEl.attr('name') + '" data-value="'+ inputRadioEl.val() +'"></div>'),
                    radioInputLabelEl = this.$el.closest('form').find('label[for="' + inputRadioEl.attr('id') + '"]');

                if (inputRadioEl.is(':checked')) {
                    radioDiv.addClass('ui-radio-selected');
                }
                if (inputRadioEl.is('disabled')) {
                    radioDiv.addClass('ui-radio-disabled');
                }
                radioDiv.on('keydown.' + this.cid + ' click.' + this.cid, _.bind(function(e){
                    if (e.type === 'keydown') {
                        this.onKeyDown(e);
                    } else {
                        this.onRadioClick(e);
                    }
                },this));

                var radioInputTabIndex = inputRadioEl.attr('tabindex');
                // set tabindex to -1 to ignore radio input when tabbing
                inputRadioEl.attr('tabindex', '-1');
                if (radioInputTabIndex) {
                    radioDiv.attr('tabindex', radioInputTabIndex);
                } else {
                    radioDiv.attr('tabindex', '0');
                }

                var divRadioLabelEl = this._buildDivRadioLabel(radioInputLabelEl);
                radioDiv.append(divRadioLabelEl);
                radioInputLabelEl.hide();

                radioDiv.insertAfter(inputRadioEl);
                return radioDiv;
            },

            /**
             * Builds div-version of radio label
             * @param radioInputLabelEl
             * @returns {*|HTMLElement}
             * @private
             */

            _buildDivRadioLabel: function(radioInputLabelEl){
                var divLabel = $('<span class="ui-radio-label"></span>');
                if (radioInputLabelEl.length) {
                    // move label text inside of new div label
                    divLabel.text(radioInputLabelEl.text());
                } else {
                    // if no label, use radio input value as label
                    divLabel.text(this.$el.val());
                }
                return divLabel;
            },

            /**
             * Check
             */
            select: function(){
                if (!this.radioDivs) {
                    this.radioDivs = this.$el.closest('form').find('div.ui-radio[data-name=' + this.$el.attr('name') + ']');
                }
                this.radioDivs.removeClass('ui-radio-selected');
                this.radioDiv.addClass('ui-radio-selected');
                if (this.options.onClick) {
                    this.options.onClick();
                }
            },

            onKeyDown: function(e){
                var keycode = (e.keyCode ? e.keyCode : e.which);
                if (keycode === 32 || keycode === 13) {
                    // spacebar or enter key
                    e.preventDefault();
                    this.onRadioClick(e);
                }
            },

            /**
             * When the div-version of radio button is clicked.
             */
            onRadioClick: function(e) {
                e.preventDefault();
                if (!this.radioDiv.hasClass('ui-radio-selected')) {
                    this.select();
                    this.$el.prop('checked', true);
                }

            },
            /**
             * When the input radio button is clicked.
             */
            onRadioInputClick: function(e){
                this.onRadioClick(e);
            },

            destroy: function(removeEl) {
                this.radioDiv.off('.' + this.cid);
                this.radioDiv.remove();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return RadioButton;
    }
);
/**
 * @fileoverview Generic forms view for common site-wide form element handling.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 */
define('form',[
    'jquery',
    'underscore',
    'baseview',
    'views/modules/form/input-field',
    'views/modules/form/autocomplete',
    'views/modules/form/select-dropdown',
    'views/modules/form/select-button-toggle',
    'views/modules/form/checkbox',
    'views/modules/form/radio-button'
],
    function(
        $,
        _,
        BaseView,
        InputField,
        AutoComplete,
        SelectDropdown,
        SelectButtonToggle,
        CheckBox,
        RadioButton
        ) {
        

        /**
         * View class.
         */
        var FormView = BaseView.extend({

            events: {
                'submit':'onFormSubmit'
            },

            /**
             * Initialize the view.
             */
            initialize: function(options) {
                options = $.extend({
                    formOptions: null, //custom options
                    onSubmit: null //callback when form is submitted (i.e. function(submittedValues){})
                }, options);

                BaseView.prototype.initialize.call(this, options);

                this.$('.ui-text-input, .ui-dropdown, .ui-button-toggle, .ui-radio, .ui-checkbox').each(_.bind(function(index, el) {
                    var $el = $(el),
                        options;
                    if (this.options.formOptions) {
                        options = this._getCustomOptions($el, this.options.formOptions);
                    }
                    if ($el.hasClass('ui-text-input')) {
                        if ($el.data('autocomplete-url')){
                            // autocomplete field!
                            this._setupView($el, AutoComplete, index, 'autocomplete', options);
                        } else {
                            // input field (non-autocomplete)!
                            this._setupView($el, InputField, index, 'input', options);
                        }
                    } else if ($el.hasClass('ui-button-toggle')) {
                        // button toggle!
                        this._setupView($el, SelectButtonToggle, index, 'btoggle', options);

                    } else if ($el.hasClass('ui-dropdown')) {
                        // dropdown!
                        this._setupView($el, SelectDropdown, index, 'select_dropdown', options);

                    } else if ($el.hasClass('ui-radio')) {
                        // radio button!
                        this._setupView($el, RadioButton, index, 'radio', options);

                    } else if ($el.hasClass('ui-checkbox')) {
                        // checkbox!
                        this._setupView($el, CheckBox, index, 'checkbox', options);

                    }
                },this));

            },

            /**
             * Checks and returns whether form element has custom options
             * @param {JQuery} $el Element used to determine a match
             * @param {Object|Array} options Options to match el against
             */
            _getCustomOptions: function($el, options){
                // function to find matching options
                var matchingOptions = function(obj){
                    if ($el[0] === $(obj.el)[0]) {
                        // it's a match!
                        return true;
                    } else {
                        return false;
                    }
                };
                // if it is an array, lets filter it down to one
                if ($.isArray(options)) {
                    return _.filter(options, function(obj){
                        return matchingOptions(obj);
                    })[0];
                } else if ($.isPlainObject(options)) {
                    if (matchingOptions(options)) {
                        return options;
                    } else {
                        return false;
                    }
                }

            },

            /**
             * Instantiates views
             * @param {JQuery} $el Jquery object el
             * @param {Object} View Backbone view to instantiate
             * @param {Number} index Subview index
             * @param {String} subviewName Name of the subview
             * @param {Object} options Options to use when instantiating
             */
            _setupView: function($el, View, index, subviewName, options){
                if (!options) {options = {el: $el };}
                this.subviews[subviewName+index] = new View(options);
            },

            /**
             * Processes placeholders
             * @param {Array} items Array of Jquery objects to process
             */
            handlePlaceholders: function(items){
                var resetMap = [];
                // Let's temporarily remove placeholders so they don't get submitted with form
                $.each(items, function(index, el){
                    var field = $(el),
                        value = field.val();
                    if (value === field.attr('placeholder')) {
                        resetMap.push({field: field, value: value});
                        field.val('');
                    }
                });
                // after the submit is done, restore the original placeholder values
                _.defer(function(){
                    _.each(resetMap, function(itm){
                        itm.field.val(itm.value);
                    });
                });
            },


            callToSubView: function(elClass, method, args) {
                var subviewName;
                _.each(this.subviews, function(value, key){
                    if (value.$el.hasClass(elClass)) {
                        subviewName = key;
                    }
                });
                if (subviewName) {
                    this.subviews[subviewName][method](args);
                }
            },


            /**
             * When form is submitted.
             */
            onFormSubmit: function(e) {
                var submittedValues = {};

                if (!Modernizr.input.placeholder) {
                    var itemsWithPlaceholders = this.$('[placeholder*=""]');
                    if (itemsWithPlaceholders) {
                        this.handlePlaceholders(itemsWithPlaceholders);
                    }
                }

                if (this.options.onSubmit) {
                    // put submitted values into a nice little object to be returned
                    _.each(this.$el.serializeArray(), function(obj){
                        submittedValues[obj.name] = obj.value;
                    });
                    this.options.onSubmit(submittedValues);
                }

            },

            /**
             * Resets entire form back to original state.
             */
            resetForm: function() {
                this._callCollection(this.subviews, 'resetInput');
            },

            destroy: function(){
                BaseView.prototype.destroy.apply(this, arguments);
            }
        });

        /**
         * Return view class.
         */
        return FormView;
    }
);

/**!
 * @preserve Color animation 20120928
 * http://www.bitstorm.org/jquery/color-animation/
 * Copyright 2011, 2012 Edwin Martin <edwin@bitstorm.org>
 * Released under the MIT and GPL licenses.
 */

(function($) {
    var properties = ['color', 'backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'outlineColor'];
    $.each(properties, function(i, property) {
        $.Tween.propHooks[ property ] = {
            get: function(tween) {
                return $(tween.elem).css(property);
            },
            set: function(tween) {
                var style = tween.elem.style;
                var p_begin = parseColor($(tween.elem).css(property));
                var p_end = parseColor(tween.end);
                tween.run = function(progress) {
                    style[property] = calculateColor(p_begin, p_end, progress);
                };
            }
        };
    });

    // borderColor doesn't fit in standard fx.step above.
    $.Tween.propHooks.borderColor = {
        set: function(tween) {
            var style = tween.elem.style;
            var p_begin = [];
            var borders = properties.slice(2, 6); // All four border properties
            $.each(borders, function(i, property) {
                p_begin[property] = parseColor($(tween.elem).css(property));
            });
            var p_end = parseColor(tween.end);
            tween.run = function(progress) {
                $.each(borders, function(i, property) {
                    style[property] = calculateColor(p_begin[property], p_end, progress);
                });
            };
        }
    };

    // Calculate an in-between color. Returns "#aabbcc"-like string.
    function calculateColor(begin, end, pos) {
        var color = 'rgb' + (Modernizr.rgba ? 'a' : '') + '('
            + parseInt((begin[0] + pos * (end[0] - begin[0])), 10) + ','
            + parseInt((begin[1] + pos * (end[1] - begin[1])), 10) + ','
            + parseInt((begin[2] + pos * (end[2] - begin[2])), 10);
        if (Modernizr.rgba) {
            color += ',' + (begin && end ? parseFloat(begin[3] + pos * (end[3] - begin[3])) : 1);
        }
        color += ')';
        return color;
    }

    // Parse an CSS-syntax color. Outputs an array [r, g, b]
    function parseColor(color) {
        var match, triplet;

        // Match #aabbcc
        if (match = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(color)) {
            triplet = [parseInt(match[1], 16), parseInt(match[2], 16), parseInt(match[3], 16), 1];

            // Match #abc
        } else if (match = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(color)) {
            triplet = [parseInt(match[1], 16) * 17, parseInt(match[2], 16) * 17, parseInt(match[3], 16) * 17, 1];

            // Match rgb(n, n, n)
        } else if (match = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) {
            triplet = [parseInt(match[1]), parseInt(match[2]), parseInt(match[3]), 1];

        } else if (match = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9\.]*)\s*\)/.exec(color)) {
            triplet = [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10),parseFloat(match[4])];

            // No browser returns rgb(n%, n%, n%), so little reason to support this format.
        }
        return triplet;
    }
})(jQuery);
define("animatecolors", function(){});


/**
 * @fileoverview Weather panel dropdown in the global navigation.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/weather/weather-dropdown',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app',
    'state',
    'views/modules/form/autocomplete',
    'easing',
    'animatecolors',
    'cookie'
],
    function(
        $,
        _,
        Backbone,
        BaseView,
        PubSub,
        App,
        StateManager,
        AutoComplete
        ) {
        
        /**
         * View class.
         */
        var WeatherDropdownView = BaseView.extend({

            // View element.
            el: '.weather-nav-dropdown',

            // Events.
            events: {
                'hover':'onHoverDropdown',
                'click .weather-nav-dropdown-settings-open-btn': 'showSettingsPanel',
                'click .weather-nav-dropdown-settings-close-btn': 'hideSettingsPanel',
                'click .weather-nav-location-cancel-btn': 'hideSettingsPanel',
                'click .weather-nav-location-set-btn': 'onSetButtonClick',
                'submit .weather-nav-location-form': 'onSubmitLocationForm',
                'keydown .weather-nav-location-input':'onKeyDown',
                'focus .weather-nav-location-input' : 'onFocusLocationField',
                'blur .weather-nav-location-input' : 'onBlurLocationField',
                'click .weather-nav-full-forecast-btn': 'onClickFullForecast'
            },

            /**
             * Initialize the view.
             */
            initialize: function(options) {

                _.bindAll(this, 'refreshData', 'openDropdown', 'closeDropdown','_parseData', 'onAutoCompleteResultClick', 'showLocationInputError', 'clearLocationInputError');

                this.panels = this.$('.weather-nav-dropdown-panel-wrap');
                this.frontPanel = this.panels.find('.weather-nav-conditions-panel');
                this.frontWeatherLocation = this.frontPanel.find('.weather-nav-location-name');
                this.frontWeatherIcon = this.frontPanel.find('.weather-nav-dropdown-wicon');
                this.settingsPanel = this.panels.find('.weather-nav-settings-panel');
                this.locationField = this.settingsPanel.find('.weather-nav-location-input');
                this.dropdownWiconClassName = this.frontWeatherIcon.attr('class');
                this.transitionDelay = 80;

                this.body = App.get('body');
                this.navBtn = this.$el.parent('.weather');
                this.navBtnTemp = this.navBtn.find('.btn-temp');
                this.navBtnClassName = this.navBtnTemp.attr('class');
                this.pubSub = {
                    'weather:newLocation': this._parseData
                };
                BaseView.prototype.initialize.call(this, options);
                if (!$.cookie('weatherLocation')) {
                    this.updateWeatherLocation('McLean, VA');
                } else {
                    this.refreshData();
                }
                // Setup to refresh weather data every 5 minutes.
                this.weatherDataRefresh = setInterval(this.refreshData, 300000);
                this.locationErrorEl = this.$('.weather-nav-location-error');

            },

            /**
             * Click handler for weather dropdown form submit button.
             * @param {Event} e Click event.
             */
            onSetButtonClick: function(e) {
                e.preventDefault();
                this.updateWeatherLocation(this.locationField.val());
            },

            /**
             * When autocomplete result item is clicked.
             */
            onAutoCompleteResultClick: function() {
                this.updateWeatherLocation(this.locationField.val());
            },

            /**
             * Handler for typing.
             * @param {Event} e Event
             */
            onKeyDown: function(e) {
                var keycode = (e.keyCode ? e.keyCode : e.which);
                // enter key
                if (keycode === 13){
                    this.updateWeatherLocation(this.locationField.val());
                }
                this.clearLocationInputError();
            },

            /**
             * Submit handler for weather dropdown form.
             * @param {Event} e Submit event.
             */
            onSubmitLocationForm: function(e) {
                e.preventDefault();
            },

            /**
             * Click handler for full forecast link.
             * @param {Event} e Click event.
             */
            onClickFullForecast: function(e) {
                this.isMouseOnDropdown = false;
                this.closeDropdown();
            },


            /**
             * Hover handler for dropdown area.
             * @param {Event} e Hover event.
             */
            onHoverDropdown: function(e){
                if (e.type === 'mouseenter'){
                    this.isMouseOnDropdown = true;
                } else if (!this.locationField.is(':focus')) {
                    this.isMouseOnDropdown = false;
                    this.closeDropdown();
                }
            },

            /**
             * Close weather dropdown.
             */
            closeDropdown: function() {
                if (this.isMouseOnDropdown) {
                    return;
                }
                if (this.isSettingsPanelActive) {
                    this.hideSettingsPanel();
                }
                StateManager.registerAnimation(this.$el.stop().fadeOut(this.transitionDelay, 'swing').promise().done(_.bind(function(){
                    this.$el.removeClass('dropdown-active');
                    this.navBtn.find('.nav-span').removeClass('dropdown-active');

                },this)));
                this.body.off('.'+ this.cid);
            },

            /**
             * Open weather dropdown.
             */
            openDropdown: function() {
                // we need to add class to navbtn
                StateManager.registerAnimation(this.$el.stop().fadeIn(this.transitionDelay, 'swing').promise().done(_.bind(function(){
                    this.$el.addClass('dropdown-active');
                    this.navBtn.find('.nav-span').addClass('dropdown-active');
                },this)));
            },

            /**
             * Show weather settings panel.
             */
            showSettingsPanel: function() {
                if (!this.$el.hasClass('settings-active')) {
                    this.$el.addClass('settings-active');
                    this.isSettingsPanelActive = true;
                }
                if (!this.subviews.autocomplete) {
                    this.subviews.autocomplete = new AutoComplete({
                        el: this.locationField,
                        resultDisplayTemplate: '<%= City %>, <%= State %>',
                        resultValueTemplate: '<%= City %>, <%= State %>',
                        onSelect: this.onAutoCompleteResultClick
                    });
                }
            },

            /**
             * Hide weather settings panel.
             */
            hideSettingsPanel: function() {
                if (this.subviews.autocomplete) {
                    this.subviews.autocomplete.resetInput();
                }
                this.clearLocationInputError();
                this.locationField.blur();
                if (this.$el.hasClass('settings-active')) {
                    this.$el.removeClass('settings-active');
                    this.isSettingsPanelActive = false;
                }

            },

            /**
             * Handles focus of location field.
             */
            onFocusLocationField: function(e) {
                this.locationField.val('');
                //add click event to body for clicks outside of the dropdown div
                this.body.on('click.'+ this.cid, _.bind(function(e){
                    // This is testing if the clicked item's parents do not contain this.el.
                    // We do this because we only want to close the dropdown if you're clicking outside this.el
                    if($(e.target).closest(this.el).length === 0) {
                        this.isMouseOnDropdown = false;
                        this.closeDropdown();
                    }
                },this));
            },

            /**
             * Handles blur of location field.
             */
            onBlurLocationField: function(e) {
                this.locationField.val(this.locationField.data('value'));
            },

            /**
             * Set weather cookie.
             * @param {String} location weather location.
             */
            setWeatherCookie: function(location) {
                $.cookie('weatherLocation', location, {path:'/',expires:1825});
            },

            /**
             * Get weather dropdown data.
             * @param {String} location weather location.
             */
            updateWeatherLocation: function(location) {
                if (!location || location === $.cookie('weatherLocation')){
                    return;
                }
                return this._fetchData(location).done(_.bind(function(data){
                    this.hideSettingsPanel();
                    PubSub.trigger('weather:newLocation', data);
                },this)).fail(_.bind(function(errorMsg){
                    this.showLocationInputError(errorMsg);
                },this));
            },

            /**
             * Refresh weather dropdown data.
             */
            refreshData: function() {
                return this._fetchData($.cookie('weatherLocation'));
            },

            /**
             * Fetch weather dropdown data.
             * @param {String} location weather location.
             */
            _fetchData: function(location) {
                location = location.replace(',','');

                if (this.isBusyGettingData) {
                    return $.Deferred().reject();
                }
                this.isBusyGettingData = true;
                return $.Deferred(_.bind(function(defer){
                    StateManager.fetchData('/services/weather/forecast/json/' + location + '/')
                        .done(_.bind(function(data){
                            if (data.length && data[0]) {
                                this._parseData(data);
                                defer.resolveWith(this, [data]);
                            } else {
                                defer.rejectWith(this,['No data is available for this location.']);
                            }
                            this.isBusyGettingData = false;
                        },this))
                        .fail(_.bind(function(){
                            defer.rejectWith(this,['There was an error finding this location. Please try again later.']);
                            this.isBusyGettingData = false;
                        },this));
                },this));
            },

            /**
             * Shows error message.
             * @param {String} message Error message
             */
            showLocationInputError: function(message) {
                if (this.locationErrorEl.html() !== message) {
                    this.locationErrorEl.addClass('ui-input-field-error-active');
                    this.locationErrorEl.text(message);
                    this.locationErrorEl.stop().slideDown(50, 'easeInOutQuad');
                }
            },

            /**
             * Clears error.
             */
            clearLocationInputError: function(){
                if (this.locationErrorEl.hasClass('ui-input-field-error-active')) {
                    this.locationErrorEl.stop().slideUp(50, 'easeInOutQuad').promise().done(_.bind(function() {
                        this.locationErrorEl.removeClass('ui-input-field-error-active');
                        this.locationErrorEl.empty();
                    },this));
                }
            },

            /**
             * Parse weather dropdown response and append/show/hide.
             * @param {Object} data object which contains weather data.
             */
            _parseData: function(data) {
                if (!data[0].currentconditions){
                    return;
                }
                var result = data[0],
                    currentConditions = result.currentconditions,
                    location = result.local.city + ', ' + result.local.adminArea.code,
                    weatherIconClass = 'wicon-'+currentConditions.weathericon,
                    temp = currentConditions.temperature;

                // loop over the html, looking for data-weather attributes which signifies that weather data goes there
                this.$('[data-weather]').each(_.bind(function(idx, item){
                    var $item = $(item);
                    $item.html((currentConditions[$item.data('weather')] || '') + ($item.data('weather-suffix') || ''));
                }, this));

                // add special class for long location names
                if (location.length > 20) {
                    this.frontWeatherLocation.addClass('longname');
                }
                this.frontWeatherLocation.html(location);
                // add special class for temperatures longer than two digits
                if (temp > 99) {
                    this.frontWeatherTemp.addClass('three-digit');
                }
                // clear out previous icon class and add new one
                this.frontWeatherIcon.attr('class',this.dropdownWiconClassName+' '+weatherIconClass);

                this.navBtnTemp.attr('class',this.navBtnClassName+' '+weatherIconClass);
                this.navBtnTemp.html(temp+this.navBtnTemp.data('weather-suffix'));
                // add class to show dropdown now that we have data
                this.navBtn.addClass('has-data');
                if ($.cookie('weatherLocation') !== location) {
                    this.setWeatherCookie(location);
                }
                this.locationField.data('value', location).val(location);


            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             */
            destroy: function(removeEl) {
                this.body.off('.' + this.cid);
                clearInterval(this.weatherDataRefresh);
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });


        /**
         * Return view class.
         */
        return WeatherDropdownView;
    }
);

/**
 * @fileoverview Single Video module view.
 * @author Chris Manning
 * @author Jay Merrifield
 * @author Brendan Bagley
 */
/*global APIModules:true*/
define('views/modules/video',['jquery', 'underscore', 'baseview', 'pubsub','state'],
    function($, _, BaseView, PubSub, StateManager) {
        

        /**
         * View class.
         */
        var VideoView = BaseView.extend({

            // Events.
            events: {
                'click .videoStillPlay': 'swapImageForVideo',
                'click .videoCloseButton': 'hidePlayer'
            },

            /**
             * Fired on new VideoView
             */
            initialize: function(options) {
                if (!options || !options.el) {return;}
                options = $.extend(true, {
                    onVideoComplete:null,
                    onVideoShow:null,
                    onVideoHide:null
                    }, options);
                this.scriptsLoaded = false;
                this.liveHidden = false;
                this.videoDetail={};
                this.player=false; 
                this.modVP=false;
                this.modExp=false; 
                this.$videoObj = this.$('.videoObject');
                this.brightcoveId = this.$('.BrightcoveExperience').attr('id');
                if (!this.$videoObj.length || !this.brightcoveId){
                    // this probably means we've been instantiated on the wrong element
                    return;
                }
                this.inited = true;
                this.tenpercent=false;
                this.fiftypercent=false;
                this.ninetyfivepercent=false;
                this.throttledDetermine = _.throttle(this.determineCompletion, 1500);
                this.live=false;

                _.bindAll(this, 'createPlayer', 'onBrightCoveLoad', 'onVideoComplete', 'getVideoDetail', 'onVideoStart', 'destroy', 'isPlayingHandler', 'determineCompletion');

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
                if (this.options.autostart || this.options.autocreate || this.$('.BrightcoveExperience').attr('data-autoplay')) {                    
                    this.createPlayer();
                }
                if(this.options.live) {
                    this.live=true;
                }

                this._buildBrightCoveLoadCallback();
            },

            _buildBrightCoveLoadCallback: function(){
                if (!window.BCCallbacks){
                    window.BCCallbacks = {};
                }
                window.BCCallbacks[this.brightcoveId] = this.onBrightCoveLoad;
                if (!window.BCLoad) {
                    window.BCLoad = function(experienceId){
                        if (window.BCCallbacks[experienceId]){
                            window.BCCallbacks[experienceId](experienceId);
                        }else{
                            console.warning('received brightcove callback for video that does not exist: ' + experienceId);
                        }
                    };
                }
            },

            /*
            * Sets BC experience variables & event listeners through SmartPlayer API
            */
            onBrightCoveLoad: function(experienceId) {
                //loading indicator for the scripts on our end
                this.$('.temp-loader').fadeOut();
                this.player = window.brightcove.api.getExperience(experienceId);
                if (!this.player){
                    console.warn('brightcove video loaded, but could not get experience: ' + experienceId);
                }else{
                    console.log("brightcove loaded successfully", this.brightcoveId);
                    this.modVP = this.player.getModule(window.brightcove.api.modules.APIModules.VIDEO_PLAYER);
                    if (this.modVP && window.site_config.SMARTPLAYER){
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.BEGIN, this.onVideoStart);
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.COMPLETE, this.onVideoComplete);
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.PLAY, this.onMediaEventFired);
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.STOP, this.onMediaEventFired);
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.SEEK_NOTIFY, this.onMediaEventFired);
                        this.modVP.addEventListener(window.brightcove.api.events.MediaEvent.PROGRESS, this.throttledDetermine);
                    }
                }
            },

            /*
             * Finish gathering analytics info and fire PubSub event
             */
            onVideoStart : function(evt) {
                if(evt.duration<120) {
                    this.videoDetail.videoDuration="less than 2 min";
                }
                else {
                    this.videoDetail.videoDuration="greater than 2 min";
                }
                this.videoDetail.completion = '0%';
                if(this.videoDetail.liveVideoSubject) {
                    this.videoDetail.videoName=this.videoDetail.liveVideoSubject;
                }
                else {
                    this.videoDetail.videoName = evt.media.displayName;
                }
                this.videoDetail.eventtype = 'video:load';
                this.videoDetail.contentid = evt.target.experience.id;
                this.videoDetail.videoFulllengthUrl = evt.media.FLVFullLengthURL;

                PubSub.trigger('video:load', this.videoDetail);
            },

            onVideoComplete: function(){
                console.log('video playback finished: ' + this.brightcoveId);
                if ($.isFunction(this.options.onVideoComplete)){
                    this.options.onVideoComplete();
                }
            },

            //handler for BrightCove smart player API media events
            onMediaEventFired: function(evt) {
                PubSub.trigger('uotrack', evt.type);
            },

            determineCompletion: function(evt) {
                var dur = evt.duration,
                    pos = evt.position,
                    percentage=Math.round( pos/dur*100);
                if(!this.fiftypercent && percentage >=50 && percentage <95){
                    PubSub.trigger('vitrack', "50%");
                    this.fiftypercent=true;
                } 
                else if(!this.ninetyfivepercent && percentage >=95 && percentage <99){
                    PubSub.trigger('vitrack', "95%");
                    this.ninetyfivepercent=true;
                } 
            },

            /**
             * Render Brightcove Player
             */
            createPlayer: function() {
                if (window.brightcove) {
                    //start gathering metadata for analytics
                    this.getVideoDetail();
                    var sidebarBtn = $('.open-sidebar');
                    if (sidebarBtn.is(':visible') && $('#overlay').length === 0) {
                        sidebarBtn.hide();
                        this.liveHidden = true;
                    }

                    window.brightcove.createExperiences(null, this.brightcoveId);

                    StateManager.stopRefreshTimer();
                    this.$videoObj.show();
                } else {
                    //we need to require the Brightcove JS
                    this.loadScripts(this.createPlayer);
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {Boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl, paused) {
                //make sure we're initialized
                if (this.inited){
                    StateManager.startRefreshTimer();
                    //make sure we have a brightcove ID and object at the window level
                    if (this.brightcoveId && window.brightcove) {
                        //make sure we have a player for this instance
                        if(!this.player) {
                            if (typeof window.brightcove.api !== 'undefined') {
                                this.player = window.brightcove.api.getExperience(this.brightcoveId);
                            }
                        }
                        if (this.player){
                            //make sure we have a SmartPlayer API video player module
                            if(!this.modVP) {
                                this.modVP = this.player.getModule(window.brightcove.api.modules.APIModules.VIDEO_PLAYER);
                            }
                            if(this.modVP && window.site_config.SMARTPLAYER) {
                                //check if video is still playing and handle                               
                                this.modVP.getIsPlaying(this.isPlayingHandler);
                                //remove SmartPlayer API event listeners
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.BEGIN, this.onVideoStart);
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.COMPLETE, this.onVideoComplete);
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.PLAY, this.onMediaEventFired);
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.STOP, this.onMediaEventFired);
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.SEEK_NOTIFY, this.onMediaEventFired);
                                this.modVP.removeEventListener(window.brightcove.api.events.MediaEvent.PROGRESS, this.throttledDetermine);
                            }
                        }
                        // clean up the memory leak that brightcove creates
                        // they hold a brightcoveId -> dom map that they never clear
                        if (window.brightcove) {
                            if (window.brightcove.experiences) {
                                delete window.brightcove.experiences[this.brightcoveId];
                            }
                            if (window.brightcove.instances) {
                                delete window.brightcove.instances[this.brightcoveId];
                            }
                        }

                    }
                    if (!window.BCCallbacks){
                        console.warn('BCCallbacks no longer available on video destroy');
                    }else{
                        if (window.BCCallbacks[this.brightcoveId]){
                            // remove brightcove callback
                            delete window.BCCallbacks[this.brightcoveId];
                        }
                        // if we're the last callback, cleanup the callback manager
                        if (_.size(window.BCCallbacks) === 0){
                            window.BCCallbacks = undefined;
                            window.BCLoad = undefined;
                            try {
                                delete window.BCCallbacks;
                                delete window.BCLoad;
                            } catch (e) {} // guard against IE throwing exceptions
                        }
                    }
                }
                BaseView.prototype.destroy.apply(this, arguments);
            },

            /**
             * Hide Brightcove Player
             */
            hidePlayer: function() {
                if (this.liveHidden) {
                    $('.open-sidebar').show();
                    this.liveHidden = false;
                }
                if (this.$videoObj) {
                    this.$videoObj.hide();
                }
                if ($.isFunction(this.options.onVideoHide)){
                    this.options.onVideoHide();
                }
                StateManager.startRefreshTimer();
            },

            /**
             * Load Brightcove Player script dependencies
             */
            loadScripts: function(callback) {
                require(['http://admin.brightcove.com/js/BrightcoveExperiences.js'], function() {
                    // Script creates window.brightcove object we need to create video flash players.
                    if (typeof window.brightcove !== 'undefined') {
                        callback();
                        console.log('loading Brightcove');
                    } else {
                        console.log('Error loading Brightcove');
                    }
                });
            },

            /* Replace the video still with an actual video player
             * @param {Event} e Browser event
             */
            swapImageForVideo: function(e){
                if (this.$el.closest('.hero').length && $(e.target).is("a")) {
                    return;
                }
                this.createPlayer();
                if ($.isFunction(this.options.onVideoShow)){
                    this.options.onVideoShow();
                }

                // Loading indicator for the scripts on our end
                this.$('.temp-loader').show();
                PubSub.trigger('video:playClick');
            },

            /* Pulls in relevant metadata for analytics calls
             */
            getVideoDetail: function() {
                this.videoDetail.videoPlayerName = this.$('.vpname').val();
                this.videoDetail.videoContentProvider = this.$('.vcp').val();
                this.videoDetail.keywords = this.$('.vtags').val();
                this.videoDetail.ssts = this.$('.ssts').val();
                this.videoDetail.cst = this.$('.cst').val();
                this.videoDetail.assetid = this.$('.assetid').val();
                this.videoDetail.templateType = this.$('.templatetype').val();
                this.videoDetail.contenttype = this.$('.contentType').val();
                this.videoDetail.pageURL = this.$('.pageURL').val();
                this.videoDetail.liveVideoSubject = this.$('.liveVideoSubject').val();
                this.videoDetail.pathName='';
                if(this.videoDetail.liveVideoSubject) {
                    this.videoDetail.pathName =  this.videoDetail.liveVideoSubject;
                }
                else if(this.videoDetail.pageURL) {
                    this.videoDetail.pathName =  this.videoDetail.pageURL.replace(/^.*\/\/[^\/]+/, '');
                }

                try {
                    if(!_.isUndefined(this.videoDetail.cst)) {
                        this.videoDetail.cstlist= this.videoDetail.cst.split('/');
                        this.videoDetail.category= this.videoDetail.cstlist[0];
                        this.videoDetail.cst= this.videoDetail.cstlist.slice(0,3).join(':');
                        this.videoDetail.subcategory= this.videoDetail.cstlist.slice(0,2).join(':');
                    }
                    if(!_.isUndefined(this.videoDetail.sstslist)) {
                        this.videoDetail.sstslist= this.videoDetail.ssts.split('/');
                        this.videoDetail.section= this.videoDetail.sstslist[0];
                        this.videoDetail.ssts= this.videoDetail.sstslist.join(':');
                        this.videoDetail.subsection= this.videoDetail.sstslist.slice(0,2).join(':');
                        this.videoDetail.topic= this.videoDetail.sstslist.slice(0,3).join(':');
                    }
                } catch (er) {
                    console.error('Invalid page', er.stack || er.stacktrace || er.message);
                    return;
                }
            },

            /* Receives playing status from Brightcove API function and pauses video, if needed
             */
            isPlayingHandler: function(result) {
                if(!this.live) {
                    if(result) {
                        this.modVP.pause(true);
                    }
                }
            }

        });

        /**
         * Return view class.
         */
        return VideoView;
    }
);
/**
 * @fileoverview Generic element handling live videos. 
 */
define('views/modules/livevideo',['jquery', 'underscore', 'backbone', 'pubsub','state', 'app','views/modules/video'],
    function($, _, Backbone, PubSub, StateManager,App,Video) {


        /**
         * View class.
         */
        var LiveVideoView = Backbone.View.extend({

            events:{
                'click #close_modal_link': 'close'
            },
            /**
             * Initialize the view.
             */
            initialize: function() {
                this.m_uiModal={};
                this.m_uiModalBgrnd={}; 
                this.win = App.get('win')[0]; 
                this.body = App.get('body');
                StateManager.registerFullScreenView(this);
                this.win.gannett = {}; // we need this because player is going to fire this method on popout
                var _this=this;
                this.win.gannett.videoplayer_modal = {

                openPopup:function(){ 
                        var URL = '/livevideos/popout/';
                        var description= $("#videoplayer_modal .video-title").text();
                        var sponsor= $("#videoplayer_modal .sponsor-text").text();
                        var sourcelogo= $("#videoplayer_modal .video-logo").attr("src");
                        var vid= $("#videoplayer_modal").attr('data-assetid');

                        URL += "?videoid="+vid+"&description="+description+"&sponsor="+sponsor+"&sourcelogo="+sourcelogo;
                        if(vid) {
                            App.openPopup(URL,310, 260);
                            _this.close();
                        }
                       
                }

                };
            }, 
            /**
             * load the live video content to the dom 
             * @param assetid {id}  VPC asset id for live video
             */
            loadLiveVideo:function(assetid){
                var _this = this;
                StateManager.fetchHtml('/services/livevideos/'+assetid).done(function(r){
                    _this.body.append(r);
                    _this.video = new Video({
                        el:  $("#videoplayer_modal"),
                        autostart: true,
                        live: true
                    });
                   _this.m_uiModal = $("#videoplayer_modal");
                   _this.m_uiModalBgrnd = $("#lightbox");

                   _this.m_uiModal.show();
                   _this.m_uiModalBgrnd.fadeIn(300);
                    _this.setElement('#videoplayer_modal');
                });
            },
            /**
             * closes the live video modal, null object,remvoes it from dom   
             * and also destroys unused variables.
             */
             

            close:function(){
                if(this.m_uiModal){
                    StateManager.clearFullScreenView(); 
                    var bgrnd = this.m_uiModalBgrnd;
                    this.destroy(true); 
                    this.m_uiModalBgrnd.fadeOut(300, function(){bgrnd.remove();});
                    this.m_uiModal = null;
                    this.m_uiModalBgrnd = null; 
                    this.win.gannett = {}; 
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                //lets destroy video object too 
                if (this.video){
                    this.video.destroy(true);
                }
                this.undelegateEvents();
                if (removeEl) this.remove();
            }
        });

        /**
         * Return view class.
         */
        return LiveVideoView;
    }
);

/**
 * @fileoverview Global header (nav) module view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 *         stephen.burgess@f-i.com (Stephen Burgess)
 */
 
define('views/modules/header',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'state',
    'facebook',
    'userauth',  
    'form',
    'views/modules/weather/weather-dropdown',
    'views/modules/livevideo',
    'easing',
    'animatecolors',
    'cookie'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    StateManager,
    Facebook, 
    UserAuth,
    FormView,
    WeatherDropdown,
    Livevideo
) {

        /**
         * View class.
         */
        var HeaderView = Backbone.View.extend({

            // View element.
            el: '#header',

            // Events.
            events: {
                'mouseenter #navbar .weather': 'onHoverWeatherNav',
                'mouseleave #navbar .weather': 'onHoverWeatherNav',
                'click #navbar .weather': 'onClickWeatherNav',
                'hover #navbar .user': 'onHoverUserNav',
                'click .fb-login-btn': 'onClickLogin', 
                'click .fb-logout-btn': 'onClickLogout', 
                'click .gp-login-btn': 'onClickLoginGP',
                'click .gp-logout-btn': 'onClickLogoutGP',
                'click #breaking .headline':'onClickBreakingBtn',
                'click #breaking .button':'onClickBreakingBtn',
                'click #breaking .close-btn': 'onClickCloseBreakingBtn',
                'click #nav .search': 'onClickNavSearch',
                'click .header-search-close-btn': 'cancelSearch'
            },

            /**
             * Initialize the view.
             */
            initialize: function() {

                // Cache references to common elements/calculations.
                this.win = App.get('win');
                this.body = App.get('body');
                this.scrollEl = App.get('scrollEl');
                this.fixedWrap = this.$('.fixed-wrap');
                this.logo = this.fixedWrap.find('.logo');
                this.searchWrap = this.$('.header-search-form-wrap');
                this.nav = App.get('navEl');
                this.navSearchBtn = this.nav.find('.search');
                this.breaking = App.get('breakingEl');
                this.breakingWrap = App.get('breakingWrapEl');

                // Values.
                // TODO: May want to replace these with fetched values from DOM.
                this.navHeight = this.nav.outerHeight();
                this.mastheadHeight = 80;

                // Breaking news animate colors.
                this.breakingColors = {
                    breaking : {
                        normal : 'rgb(247,0,0)',
                        highlight : 'rgb(191,49,49)'
                    },
                    live : {
                        normal : 'rgb(0,170,255)',
                        highlight : 'rgb(0,145,218)'
                    },
                    developing : {
                        normal : 'rgb(0,170,255)',
                        highlight : 'rgb(0,145,218)'
                    }
                };

                // Keep 'this' reference to view in scroll.
                _.bindAll(this);

                // Scroll event flag.
                this.preventScrollEvent = false;

                // Initialize header states.
                this.isMastheadExpanded = false;
                this.isSearchResultsOpen = this.body.hasClass('show-search');

                // Show/hide masthead speeds.
                this.slideSpeed = 200;
                App.set('headerSlideSpeed', this.slideSpeed);
                this.slideEasing = 'easeOutCubic';

                // Publish events.
                PubSub.on('created:cards', this.shiftSideCards, this);
                PubSub.on('open:searchResults', this.openSearchResults, this);
                PubSub.on('close:searchResults', this.closeSearchResults, this);
                PubSub.on('masthead:expand', this.expandMasthead, this);
                PubSub.on('masthead:collapse', this.collapseMasthead, this);

                // Breaking news poll.
                this.breakingLastUpdateClosed =
                    parseFloat($.cookie('breakingLastUpdateClosed',{path:'/'}));
                this.breakingLastItem = {
                    lastUpdate : this.breaking.data('lastupdate'),
                    type : this.breaking.data('type'),
                    content : this.breaking.find('p').eq(0).text()
                };
                // TODO: Re-enable this check once we are loading breaking news
                // data with the first page load.
                // if (this.shouldOpenBreakingBar()) {

                // Disabling breaking news - uncomment to re-instantiate
                setTimeout(this.updateBreakingBar, 1000);

                // }

                this.hoverDropdownDelay = 120;

                // Breaking news poll
                this.breakingNewsPoll = setInterval(this.updateBreakingBar,
                91000);

                //initialize weather header dropdown functionality
                this.weatherDropdown = new WeatherDropdown();
            },

            /**
             * Window scroll handler for header elements.
             * @param {Event} e Browser event triggering toggle.
             */
            onScrollWindow: function(e) {

                // Hide masthead when scrolling.
                if (!this.preventScrollEvent && !this.isSearchResultsOpen) {
                    this.collapseMasthead(true);
                }
            },

             /**
             * Breaking news click handler.
             * @param {Event} e Hover event.
             */
            onClickBreakingBtn: function(e) { 
                var href = $(e.currentTarget).attr('href');
                if (href.indexOf('livevideoassetid') > 0) {
                    var live = new Livevideo();
                    live.loadLiveVideo(href.split('#')[1].split('=')[1]);
                    return false;
                }
            },

            /**
             * Hover handler for weather nav button.
             * @param {Event} e Hover event.
             */
            onHoverWeatherNav: function(e) {
                var navBtn = $(e.currentTarget);
                clearTimeout(this.navBtnHoverDelay);
                if (navBtn.hasClass('has-data')) {
                    if (e.type === 'mouseenter'){
                        this.navBtnHoverDelay = _.delay(this.weatherDropdown.openDropdown, this.hoverDropdownDelay);
                    } else {
                        this.navBtnHoverDelay = _.delay(this.weatherDropdown.closeDropdown, this.hoverDropdownDelay);
                    }
                }

            },

            /**
             * Click handler for weather nav button.
             * @param {Event} e Click event.
             */
            onClickWeatherNav: function(e) {
                this.weatherDropdown.closeDropdown();
            },

            /**
             * Hover handler for user nav button.
             * @param {Event} e Hover event.
             */
            onHoverUserNav: function(e) {
                clearTimeout(this.userNavTimer);
                    this.userNavTimer = _.delay(this.toggleUserDropdown,
                        this.hoverDropdownDelay, undefined, e.type === 'mouseenter');
            },

            /**
             * Close user dropdown.
             * @param {boolean=} open Whether to force open the dropdown.
             */
            toggleUserDropdown: function(e, open) {
                if (this.preventScrollEvent) return;
                if (!this.userNavBtn) {
                    this.userNavBtn = this.nav.find('.user');
                }
                this.userNavBtn.toggleClass('active', open);
                if (this.userNavBtn.hasClass('active')) {
                    this.win.on('scroll', this.toggleUserDropdown);
                } else {
                    this.win.off('scroll', this.toggleUserDropdown);
                }
                return false;
            },

            /**
             * Click handler for nav search button.
             * @param {Event} e Click event.
             */
            onClickNavSearch: function(e) {
                if (this.isMastheadExpanded && !this.isSearchResultsOpen) {
                    this.collapseMasthead(true);
                } else {
                    this.expandMasthead(true);
                }
                if (e){
                    e.preventDefault();
                }
            },

            /**
             * Click handler for close button in breaking news bar.
             * @param {Event} e Click event object.
             */
            onClickCloseBreakingBtn: function(e) {
                this.closeBreakingBar(true);
                PubSub.trigger('uotrack', 'breakingnewsbarexit');
            },

            /**
             * Open search results view
             */
            openSearchResults: function() {
                // Deeplinked to search results; leave header as is.
                this.isSearchResultsOpen = true;
            },

            /**
             * Close search results view
             */
            cancelSearch: function() {
                if (this.isSearchResultsOpen){
                    StateManager.navigateToPreloadedUrl(this.originalPath);
                }
                this.closeSearchResults();
            },

            closeSearchResults: function(){
                this.collapseMasthead(true);
                this.isSearchResultsOpen = false;
                this.body.removeClass('show-search');
            },

            /**
             * Hide masthead (with slide animation).
             * @param {boolean=} animate Whether to animate closing.
             */
            collapseMasthead: function(animate) {
                if (this.isMastheadExpanded) {
                    this.isMastheadExpanded = false;
                    var props = {'height': '0'};
                    if (animate) {
                        this.searchWrap.stop().animate(props, this.slideSpeed,
                            this.slideEasing);
                    } else {
                        this.searchWrap.stop(false, true).css(props);
                    }
                    // reset search input field if user has left something in it
                    this.searchForm.resetForm();
                    this.toggleLogo(animate, false);

                    // Scroll listener.
                    this.win.off('scroll', this.onScrollWindow);
                }
            },

            /**
             * Show masthead (with slide animation).
             * @param {boolean=} animate Whether to animate closing.
             */
            expandMasthead: function(animate) {
                if (!this.isMastheadExpanded) {
                    this.isMastheadExpanded = true;
                    var props = {
                        'height': this.mastheadHeight
                    },
                    searchInput = this.$('.header-search-form-input'),
                    // iPad check
                    isIpad = navigator.userAgent.match(/iPad/i) !== null;
                    if (animate) {
                        this.searchWrap.stop().animate(
                            props,
                            this.slideSpeed,
                            this.slideEasing,
                            function() {
                                searchInput.focus();
                            }
                        );
                    } else {
                        this.searchWrap.stop(false, true).css(props);
                    }
                    this.toggleLogo(animate, true);

                    if (!this.searchForm) {
                        // Apply search form functionality.
                        this.searchForm = new FormView({
                            el: this.$('.header-search-form')
                        });
                    }
                    // don't bind scroll event for the ipad, the keyboard on the iPad triggers a scroll event                    
                    if (!isIpad) {
                        // Scroll listener.
                        this.win.on('scroll', this.onScrollWindow);
                    }
                }
            },

            /**
             * Toggle logo (with slide animation).
             * @param {boolean=} animate Whether to animate closing.
             * @param {boolean=} collapsed Whether to force a logo to be
             *     collapsed.
             */
            toggleLogo: function(animate, largeLogo) {
                if (animate) {
                    this.logo.stop().fadeOut(150, _.bind(function() {
                        this.logo.toggleClass('large', largeLogo)
                            .fadeIn(150);
                    }, this));
                } else {
                    this.logo.stop(false, true).toggleClass('large',
                        largeLogo);
                }
            },

            /**
             * Whether header height should animate.
             */
            shouldHeaderAnimate: function() {
                return App.getScrollPosition() <= 40;
            },

            /**
             * Close breaking news bar.
             * @param {boolean=} clickClose True if closing from from click, not automatically during poll.
             */
            closeBreakingBar: function(clickClose) {
                PubSub.trigger('breakingbar:before:close', this.navHeight, this.slideSpeed);
                this.isBreakingBarOpen = false;
                if (clickClose) {
                    this.breakingLastUpdateClosed = this.breakingLastItem.lastUpdate;
                    $.cookie('breakingLastUpdateClosed', this.breakingLastItem.lastUpdate, {path:'/'});
                }
                this.breakingHeight = -this.breaking.height();
                this.breaking.css('height', -this.breakingHeight);
                this.breakingWrap.css('position', 'absolute');
                this.breaking.stop().animate({'height': 0}, this.slideSpeed,
                    _.bind(function() {
                        if (!this.shouldHeaderAnimate()) this.updateHeaderMinHeight();
                        this.breaking.css('background-color', '');
                        this.breaking.hide();
                        PubSub.trigger('breakingbar:after:close');
                    }, this));
                if (this.shouldHeaderAnimate()) this.updateHeaderMinHeight(true);
                this.shiftSideCards(this.navHeight, true);
            },

            /**
             * Open breaking news bar.
             */
            openBreakingBar: function() {
                this.isBreakingBarOpen = true;
                this.breaking.show();
                this.breakingHeight = this.breakingWrap.height();
                PubSub.trigger('breakingbar:before:open', this.breakingHeight + this.navHeight, this.slideSpeed);
                var props = { 'height': this.breakingHeight };
                this.breaking.stop().animate(props, this.slideSpeed,
                    this.onCompleteOpenBreakingBar);
                if (this.shouldHeaderAnimate()) this.updateHeaderMinHeight(true);
                this.shiftSideCards(this.breakingHeight + this.navHeight, true);
            },

            /**
             * Update breaking bar after opening it.
             */
            onCompleteOpenBreakingBar: function() {
                this.breaking.css('height', 'auto');
                this.breakingWrap.css('position', 'static');
                if (!this.shouldHeaderAnimate()) this.updateHeaderMinHeight();
                PubSub.trigger('breakingbar:after:open');
            },

            /**
             * Set header min-height.
             * @param {boolean=} animate Whether to animate height change.
             */
            updateHeaderMinHeight: function(animate) {
                var breakingOffset = this.isBreakingBarOpen ?
                    this.breakingWrap.height() :
                    0;
                var height = this.navHeight + breakingOffset;
                if (animate) {
                    this.$el.stop().animate({ 'min-height': height }, this.slideSpeed);
                } else {
                    this.$el.css('min-height', height);
                }
                if (!this.shouldHeaderAnimate()) {
                    this.setScrollTop(this.win.scrollTop() +
                        this.breakingHeight);
                }
                this.busyCheckingBreakingNews = false;
            },

            /**
             * Shift side cards vertical postions.
             * @param {number} top Target top position of cards.
             * @param {boolean=} animate Whether to animate shift.
             */
            shiftSideCards: function(top, animate) {
                top = top || (this.navHeight + this.breaking.height());
                var cards = $('.card-fixed-container, #cards-offset-placeholder');
                if (animate) {
                    cards.stop().animate({'top': top}, this.slideSpeed);
                } else {
                    cards.css({'top': top});
                }
            },

            /**
             * Update breaking news bar.
             */
            updateBreakingBar: function() {
                if (this.busyCheckingBreakingNews) return;
                this.busyCheckingBreakingNews = true;
                StateManager.fetchHtml('/services/breaking-news/nav-bar/')
                    .done(this.parseBreakingNews);
            },

            /**
             * Check 'breakingLastUpdateClosed' cookie to determine whether to
             * open the breaking news bar.  This will be re-enabled once the
             * breaking news data is returned with the full page load later on.
             */
            // shouldOpenBreakingBar: function() {
            //     return this.breakingLastUpdate && this.breakingLastUpdateClosed
            //         !== this.breakingLastUpdate
            // },

            /**
             * Parse breaking news response and append/show/hide.
             * @param {string} htmlFrag HTML response text from XHR.
             */
            parseBreakingNews: function(htmlFrag) {
                var fetchedBreaking = $(htmlFrag);
                var fetchedBreakingDom = fetchedBreaking.find('p');
                var breakingFetchedItem = {
                    lastUpdate : parseFloat(fetchedBreaking.data('lastupdate')),
                    type : fetchedBreaking.data('type'),
                    content : fetchedBreaking.find('p').eq(0).text()
                }
                if (!breakingFetchedItem.lastUpdate) {
                    if (this.isBreakingBarOpen){
                        this.closeBreakingBar();
                    }
                    this.busyCheckingBreakingNews = false;
                } else if (
                            (this.breakingLastUpdateClosed !== breakingFetchedItem.lastUpdate &&
                                this.breakingLastItem.lastUpdate !== breakingFetchedItem.lastUpdate
                            ) ||
                            (!_.isEqual(this.breakingLastItem, breakingFetchedItem) && this.breakingAfterFirstLoad)
                        ) {
                    if (this.isBreakingBarOpen) {
                        this.breakingWrap.html(fetchedBreakingDom).stop();
                        var highlightColor = this.breakingColors[breakingFetchedItem.type].highlight;
                        var normalColor = this.breakingColors[breakingFetchedItem.type].normal;
                        this.breaking
                            .animate({'backgroundColor': highlightColor})
                            .animate({'backgroundColor': normalColor});
                        this.busyCheckingBreakingNews = false;
                    } else {
                        this.breakingWrap.html(fetchedBreakingDom);
                        this.breaking.attr('class', '').addClass(breakingFetchedItem.type);
                        this.openBreakingBar();
                    }
                } else {
                    this.busyCheckingBreakingNews = false;
                }
                    this.breakingLastItem = breakingFetchedItem;
                    this.breakingAfterFirstLoad = true;
            },

            /**
             * Set scrollTop without triggering scroll event.
             * @param {number} top Scroll top setting.
             */
            setScrollTop: function(top) {
                this.preventScrollEvent = true;
                this.scrollEl.scrollTop(top);
                setTimeout(_.bind(function() {
                    this.preventScrollEvent = false;
                }, this), 100);
            },

            /**
             * Click logout in the user auth dropdown.
             */
            onClickLogout: function() {
                this.toggleUserDropdown();
                PubSub.trigger('uotrack', 'headerprofilelogout');
                Facebook.logout();
            },

            /**
             * Click handler for user auth settings button.
             */
            onClickLogin: function() {
                this.toggleUserDropdown();
                Facebook.login();
                PubSub.trigger('uotrack', 'headerprofilelogin');
            } ,

            /**
             * Click handler for user auth google plus login button.
             */
            onClickLoginGP:function() {
                this.toggleUserDropdown(); 
                UserAuth.onClickLogin('googleplus');
                PubSub.trigger('uotrack', 'headerprofileGPlogin');
            },

            /**
             * Click handler for user auth google plus log out button.
             */
             onClickLogoutGP:function() {
                this.toggleUserDropdown();
                UserAuth.onClickLogout('googleplus');
                PubSub.trigger('uotrack', 'headerprofileGPlogout');
            },
            
            /**
             * Update the top navigation and jump nav states.
             * @param {String} path Path of the currently active section.
             */
            updateNavigation: function(path) {
                var mainNav = $('#nav > ul .text');
                path = App.getSectionPath(path);
                if(path === '') {
                    path = 'home';
                }

                // Update main nav.
                mainNav.removeClass('active');
                mainNav.filter('.' + path).addClass('active');
            }
        });

        /**
         * Return view class.
         */
        return HeaderView;
    }
);

/**
 * @fileoverview Taboola widget.
 * @author Chris Manning
 */
/*global _taboola:true */
define('views/modules/taboola',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'state'
],
function(
    $,
    _,
    Backbone,
    App,
    StateManager
)
    {
        

        /**
         * View class.
         */
        var Taboola = Backbone.View.extend({

            apiBase: 'http://api.taboola.com/1.0/json/usatodaydemo/',
            apiKey: '90393b522c6937bd3b1e815ead8d189cea03650',

            /**
             * Initialize view.
             */
            initialize: function(options) {
                this.options = $.extend({}, options || {});

                if (this.options.widget) {
                    App.loadScript('http://cdn.taboolasyndication.com/libtrc/usatodaydemo/loader.js', '_taboola', _.bind(this.getWidget, this));
                }
            },

            destroy: function() {
                this.remove();
            },

            registerTaboolaClick: function(itemId, itemType, responseId, placement){
                if (!placement) {
                    placement = 'below-photo';
                }
                var url = this.apiBase + 'recommendations.notify-click' +
                        '?app.type=desktop&app.apikey=' + this.apiKey + '&response.id=' + responseId +
                        '&item.type=' + itemType + '&item.id=' + itemId + '&placement=' + placement;
                new Image().src = url;
            },

            registerTaboolaVisible: function(responseId){
                var url = this.apiBase + 'recommendations.notify-visible' +
                    '?app.type=desktop' + '&app.apikey=' + this.apiKey + '&response.id=' + responseId;
                new Image().src = url;
            },

            getRelated: function(callback, sourceType, recType, count, sourceUrl, sourceID) {
                if (!callback) {
                    return;
                }
                if (!sourceType) {
                    sourceType = 'video';
                }
                if (!recType) {
                    recType = 'video';
                }
                if (!count) {
                    count = 6;
                }
                if (!sourceUrl) {
                    // We can do better than this. But most likely not until we have canonical urls.
                    sourceUrl = window.location.href;
                }
                if (!sourceID) {
                    sourceID = 0;
                }

                var svcUrl = this.apiBase + 'recommendations.get';
                svcUrl += '?output.callback=define&app.type=desktop&app.apikey=' + this.apiKey;
                svcUrl += '&source.id=' + sourceID + '&source.url=' + encodeURIComponent(sourceUrl) + '&source.type=' + sourceType + '&rec.type=' + recType + '&count=' + count;

                App.requireSingleUseScript(svcUrl).done(_.bind(function(data){
                    App.set('taboolaResponseID', data.id);
                    if (!data.list) {
                        data.list = {};
                    }
                    this.registerTaboolaVisible(data.id);
                    callback(data);
                }, this));
            },

            getWidget: function() {
                if (this.options.widget.length > 1) {
                    console.log('TABOOLA more stories');
                }

                _taboola.push({
                    notify:'newPageLoad'
                });
                _taboola.push({
                    article:'auto',
                    target_type:'mix',
                    url: window.location.href
                });

                _.each(this.options.widget, function(widget){
                    if (App.getPageUrl().indexOf('/sports/') !== -1 || App.getPageUrl().indexOf('/gameon/') !== -1) {
                        _taboola.push({
                            category: 'sports',
                            mode: widget.mode,
                            container: widget.container
                        });
                    } else {
                        _taboola.push({
                            mode: widget.mode,
                            container: widget.container
                        });
                    }
                });
            }

        });


        /**
         * Return view class.
         */
        return Taboola;
    }
);
/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
define("libs/swfobject/swfobject", function(){});

/**
 * @fileoverview Handles the IAB ad functionality.
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 * @author Chad Shryock <dshryock@gannett.com>
 */

define('views/modules/partner/iab',[
    'jquery',
    'underscore',
    'baseview',
    'libs/swfobject/swfobject'
],
function(
    $,
    _,
    BaseView
) {
    
        /**
         * View class.
         */
        var IABView = BaseView.extend({

            /**
             * Clean up the view (no argument).
             */
            destroy: function(removeEl) {
                if (this.$markup) {
                    this.$markup.remove();
                }
                BaseView.prototype.destroy.call(this, removeEl);
            },

            render: function(adData) {
                var promise;
                this.$el.addClass('iab-risingstar');
                if (adData.adCreativeType === 'flash') {
                    this.setupFlash(adData);
                } else if (adData.adCreativeType === 'image') {
                    this.setupImage(adData);
                } else if (adData.adCreativeType === 'third') {
                    promise = this.setupThirdParty(adData);
                }
                if (!promise) {
                    return $.Deferred().resolve();
                } else {
                    return promise;
                }
            },

            setupFlash: function(data) {
                var flashvars = {
                        clickTag: data.clickUrl + data.clickThruUrl
                    },
                    param = {
                        allowscriptaccess: "always",
                        wmode: "transparent"
                    },
                    attr = data.flashAttr || {},
                    flashId = _.uniqueId('flashiab_');

                this.$markup = $('<div id="' + flashId + '"></div>');
                this.$el.append(this.$markup);

                if (window.swfobject) {
                    window.swfobject.embedSWF(data.flashUrl, flashId, data.width, data.height, "9.0.0", null, flashvars, param, attr);
                }
            },

            setupImage: function(data) {
                this.$markup = $('<a href="' + data.clickUrl + data.clickThruUrl + '" target="_blank">' +
                    '<img src="' + data.imageUrl + '">' +
                    '</a>');
                this.$el.append(this.$markup);
            },

            setupThirdParty: function(data) {
                // Create the iframe which will be returned
                var iframe = document.createElement("iframe");

                iframe.src = 'about:blank';
                iframe.width = this.options.width || 0;
                iframe.height = this.options.height || 0;
                iframe.scrolling = 'no';
                iframe.marginWidth = 0;
                iframe.marginHeight = 0;
                iframe.frameBorder = 0;
                iframe.className = 'iab-iframe';

                // This is necessary in order to initialize the document inside the iframe
                this.$el[0].appendChild(iframe);

                // Initiate the iframe's document to null
                iframe.doc = null;

                // Depending on browser platform get the iframe's document, this is only
                // available if the iframe has already been appended to an element which
                // has been added to the document
                if (iframe.contentDocument) {
                    // Firefox, Opera
                    iframe.doc = iframe.contentDocument;
                } else if (iframe.contentWindow) {
                    // Internet Explorer
                    iframe.doc = iframe.contentWindow.document;
                } else if (iframe.document) {
                    // Others?
                    iframe.doc = iframe.document;
                }

                // If we did not succeed in finding the document then throw an exception
                if (!iframe.doc) {
                    throw "Document not found, append the parent element to the DOM before creating the IFrame";
                }

                // Create the script inside the iframe's document which will call the
                iframe.doc.open();
                iframe.doc.write('<!doctype html><html><head></head><body><script src="' + data.thirdPartyScript + '"></script></body></html>');
                iframe.doc.close();
                this.$markup = $(iframe);
                return $.Deferred(_.bind(function(defer){
                    this.$markup.load(function(){
                        defer.resolve();
                    });
                }, this)).promise();
            },

            onResize: function(){
                // IAB ads don't change size, so ignore this event, trust the css will keep us positioned correctly
            }
        });

        /**
         * Return view class.
         */
        return IABView;
    }
);

/**
 * @fileoverview An Ad Position on the page
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/partner/ad-position',[
    'jquery',
    'underscore',
    'baseview',
    'app',
    'admanager',
    'pubsub',
    'views/modules/partner/iab',
    'adLogger'
],
function(
    $,
    _,
    BaseView,
    App,
    AdManager,
    PubSub,
    IAB,
    AdLogger
) {
    

    var AdPosition = BaseView.extend({

        $head: $('head'),

        /**
         * Initializes the view
         * @param options
         */
        initialize: function(options) {
            options = $.extend({
                // required options
                adSizes: [],
                adPlacement: null, // name for this placement in the scheduling system (ie: high_impact)
                subSection: null, // sub section targeting for dfp (sports/nfl/etc)
                slotType: 'in',

                // optional options
                onAdReady: null,
                beforeAdRender: null
            }, options);

            _.bindAll(this, 'adReady');

            if (!this.$el.prop('id')) {
                this.$el.prop('id', _.uniqueId('ad-position-'));
            }

            // call base class initialize
            BaseView.prototype.initialize.call(this, options);

            // we set this up after initialization so we have a place to put them for destroy if we get a partnerView
            this.pubSub = {};
            this.adRendered = this.tracked = false;

            // clear out any possible width/height left over from a destroyed ad, let it vanish
            this.$el.css({width: '', height: '', display: ''});
        },

        /**
         * highImpactData:
         * {
                    adCallType : 'out',
                    adType : 'outofpage',
                    dfp : {
                        eaid : '%eaid!',
                        ecid : '%ecid!',
                        eenv : '%eenv!',
                        esid : '%esid!',
                        epid : '%epid!',
                        eadv : '%eadv!',
                        ebuy : '%ebuy!'
                    },
                    cacheBuster : '%%CACHEBUSTER%%',
                    clickUrl : '%%CLICK_URL_UNESC%%',
                    html : null,
                    script : '[%Script%]',
                    stylesheet : '[%StyleSheet%]',
                    trackVCE : '[%TrackvCE%]',
                    viewUrl : '%%VIEW_URL_UNESC%%'
             }
         */
        render: function(adData, adType) {
            this.adRendered = true;
            if (this.options.beforeAdRender) {
                this.options.beforeAdRender(adData, adType);
            }
            if (!adType && !adData) {
                this.adReady();
            } else {
                this.adType = adType; // normalized ad type
                this.adData = adData;
                AdLogger.logDebug('AdPosition HighImpact Ad recieved with type: ' + adType, adData);
                if (adType === 'risingstar') {
                    // render IAB rising star ad
                    this.subviews.partnerView = new IAB({
                        el: this.$el
                    });
                    this.subviews.partnerView.render(adData).done(_.bind(function() {
                        if (this.destroyed) {
                            return;
                        }
                        this.adReady();
                    }, this));
                    return;
                } else {
                    this.renderCustomAd(adData);
                }
            }
        },

        renderCustomAd: function(adData){
            if (!adData.dfp || !adData.dfp.ecid) {
                AdLogger.logError('invalid ad returned, no dfp/ecid found', adData);
                return;
            }
            if (adData.html) {
                this.$adEl = $(adData.html);
                this.$el.append(this.$adEl);
            }
            if (adData.stylesheet) {
                this.$stylesheet = $('<link rel="stylesheet" data-ad-stylesheet="' + adData.dfp.ecid + '" href="' + adData.stylesheet + '">');
                this.$head.append(this.$stylesheet);
            }
            if (adData.script) {
                adData.el = this.$el;
                App.requireSingleUseScript(adData.script).done(_.bind(function(PartnerView) {
                    var pubSubKey = 'partner:' + adData.dfp.ecid + ':ready';
                    if (this.destroyed){
                        return;
                    }
                    // remember the pubSub so we can unregister it on destruction
                    this.pubSub[pubSubKey] = this.trackView;
                    PubSub.on(pubSubKey, this.adReady, this);
                    try {
                        this.subviews.partnerView = new PartnerView(adData);
                    } catch (ex) {
                        AdLogger.logError('AdSlot(' + this.options.adUnit + '): ad delivered threw exception on creation', (ex.stack || ex.stacktrace || ex.message));
                    }
                }, this));
            } else {
                this.adReady();
            }
        },

        destroy: function(removeEl) {
            // put in place a placeholder so we don't shift the page around
            if (this.adRendered){
                var width = this.$el.width(), height = this.$el.height();
                this.$el.css({width: width, height: height});
                this.stopAd();
                this.destroyAdPlacement();
            }
            this.destroyed = true;
            BaseView.prototype.destroy.call(this, removeEl);
        },

        destroyAdPlacement: function(){
            if (this.subviews.partnerView) {
                this._dispatchToPartner('destroy', false);
                this.subviews.partnerView = null;
            }
            if (this.$adEl) {
                this.$adEl.remove();
                this.$adEl = null;
            } else {
                this.$('iframe').remove();
            }
            if (this.$stylesheet) {
                this.$stylesheet.remove();
                this.$stylesheet = null;
            }
        },

        getAdPlacement: function() {
            var adPlacement = this.options.adPlacement;
            if (this.options.subSection) {
                adPlacement += '/' + this.options.subSection;
            }
            return adPlacement;
        },

        getAdSizes: function() {
            return this.options.adSizes;
        },

        getSlotType: function() {
            return this.options.slotType;
        },

        /**
         * Signifies that the ad is ready, default behavior is to show the ad and trigger play,
         * is overridable by specifying onAdReady in the options
         */
        adReady: function() {
            AdLogger.logDebug('AdPosition ' + this.adType + ' ready');
            if (!this.options.onAdReady) {
                // default behavior
                this.playAd(); // playAd calls showAd()
            } else {
                // by registering onAdReady, you are taking control of the viewing of this ad.
                this.options.onAdReady(this.adData, this.adType);
            }
        },

        /**
         * Gets the creative state for this high impact ad from the session store
         * @param {Object} [defaultState] optional default state
         * @return {Object}
         */
        getCreativeState: function(defaultState) {
            if (this.adData && this.adData.dfp && this.adData.dfp.ecid) {
                return App.getSessionData('dfpc_' + this.adData.dfp.ecid, defaultState);
            } else {
                AdLogger.logWarn('Attempted to get state on non high impact ad');
            }
        },

        /**
         * Saves a state object to a session store
         * @param {Object} state object to save
         */
        setCreativeState: function(state) {
            if (this.adData && this.adData.dfp && this.adData.dfp.ecid) {
                App.setSessionData('dfpc_' + this.adData.dfp.ecid, state);
            } else {
                AdLogger.logWarn('Attempted to set state on non high impact ad');
            }
        },

        getHeight: function() {
            return this.$el.outerHeight();
        },

        getWidth: function() {
            return this.$el.outerWidth();
        },

        /**
         * Shows the ad and fires off any tracking pixels
         */
        showAd: function(width, height) {
            this.$el.show();
            this._dispatchToPartner('onShow', width, height);
            this.trackAd();
        },

        /**
         * Tells the high impact ad to resize itself
         */
        resizeAd: function(width, height) {
            this._dispatchToPartner('onResize', width, height);
        },

        /**
         * Helper function to send messages to the ad object
         * @param {String} funcName name of the function to call on the partner
         * @private
         */
        _dispatchToPartner: function(funcName) {
            var partnerView = this.subviews.partnerView;
            if (!partnerView) {
                return;
            }
            if (partnerView[funcName]) {
                try {
                    partnerView[funcName].apply(partnerView, Array.prototype.slice.call(arguments, 1));
                } catch (ex) {
                    AdLogger.logError('Ad threw an exception in function ' + funcName, (ex.stack || ex.stacktrace || ex.message));
                }
            } else {
                AdLogger.logError('Ad does not implement ' + funcName);
            }
        },

        /**
         * Tells the high impact ad to stop animating
         */
        stopAd: function() {
            this._dispatchToPartner('onStopToClose');
        },

        /**
         * Triggers tracking pixels for this ad
         * @param {jQuery} [trackDom] optional alternative id if you want to track a dom element other than the ad itself
         */
        trackAd: function(trackDom) {
            var trackDomId;
            if (this.tracked || !this.adData) {
                return;
            }
            this.tracked = true;
            if (this.adData.viewUrl) {
                // adData.viewUrl is in the format:
                // http://pubads.g.doubleclick.net/pagead/adview?ai=Bqas7at8GUda8K8-_6gH97oDwD62Qwu4CAAAAEAEg_bLvGTgAWLWo2YI9YMmGgIDspIAQugEJZ2ZwX2ltYWdlyAEJwAIC4AIA6gIoNzA3MC91c2F0b2RheS90cmFuc2l0aW9uX2dhbGxlcnkvd2VhdGhlcvgCgtIekAPQBZgDpAOoAwHQBJBO4AQBoAYf&sigh=_3Sxed4-ABo&template_id=10016309&adurl=
                // where the last parameter is a redirect url for an image
                var trackingPixel = $('<img src="' + this.adData.viewUrl + encodeURIComponent('http://www.gannett-cdn.com/static/images/pixels/pixel-transparent.png') + '" style="display:none;">');
                if (this.$adEl){
                    this.$adEl.append(trackingPixel);
                } else {
                    this.$adEl = trackingPixel;
                    this.$el.append(trackingPixel);
                }
                AdLogger.logDebug('Fired Tracking Pixel', this.adData.viewUrl);
            }
            if (this.adData.trackVCE === 'Yes' && this.adData.dfp) {
                trackDom = trackDom || this.$el;
                trackDomId = trackDom.prop('id');
                var scriptBase = this.adData.vCEUrl || 'http://b.voicefive.com/c2/6035223/rs.js',
                    vceScript = scriptBase + '#c1=3&amp;c3=' + this.adData.dfp.ebuy +
                                            '&amp;c4=' + this.adData.dfp.ecid +
                                            '&amp;c5=' + this.adData.dfp.epid +
                                            '&amp;c6=&amp;c10=1&amp;c11=' + this.adData.dfp.esid +
                                            '&amp;c13=' + AdManager.getVCESize(this.adType) + ';' +
                                            '&amp;c16=dfp&amp;ax_n=' + trackDomId;
                AdManager._createScript('vce_' + trackDomId, vceScript, trackDom);
                AdLogger.logDebug('Tracked vCE', vceScript);
            }
        },

        /**
         * Tells the ad to play, will also show the ad and fire tracking pixels if not already done
         */
        playAd: function() {
            this.showAd();
            this._dispatchToPartner('onPlay');
        }
    });
    return AdPosition;
});
/**
 * @fileoverview Builds a metered ad position on the page
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('meteredAdPosition',[
    'jquery',
    'underscore',
    'views/modules/partner/ad-position',
    'app',
    'state',
    'admanager',
    'adLogger'
],
function($,
     _,
     AdPosition,
     App,
     StateManager,
     AdManager,
     AdLogger) {
        

        var MeteredAdPosition = AdPosition.extend({
            /**
             * Initializes the view
             * @param options = { aws, pageName, pageType [ blog, card, cover, media, overlay, topic ], url }
             */
            initialize: function(options) {
                options = $.extend({
                    // required options
                    targeting: {},
                    slotType: 'out', // out of page by default for legacy purposes, no reason it can't be 'in' page
                    rateMeterId: null,
                    pageInfo: null // get targeting and adPlacement information from a pageInfo object
                }, options);

                if (options.pageInfo) {
                    options.targeting = AdManager.getPageTargeting(options.pageInfo);
                    if (options.pageInfo.aws) {
                        options.adPlacement += '/' + options.pageInfo.aws;
                    }
                }

                // call base class initialize
                AdPosition.prototype.initialize.call(this, options);
            },

            refreshPosition: function() {
                if (this.subviews.adSlot) {
                    this.destroyAdPlacement();
                    this.subviews.adSlot.setTargeting(this.options.targeting);
                    this.subviews.adSlot.refresh();
                }
            },

            /**
             * Overrides ad-position's adReady to prevent the ad from immediately showing
             * @override
             */
            adReady: function() {
                AdLogger.logDebug('AdPosition ready');
                this.isAdReady = true;
                if (this.options.onAdReady) {
                    this.options.onAdReady();
                }
            },

            getDefaultThreshold: function() {
                var thresholdType = this.options.meterThreshold || this.options.adPlacement,
                    split = thresholdType.indexOf('/');
                if (split !== -1) {
                    thresholdType = thresholdType.substring(0, split);
                }
                var defaultThreshold = window.site_config.ADS.THRESHOLDS[thresholdType.toUpperCase()];
                if (!defaultThreshold) {
                    AdLogger.logError('Could not find default threshold for metered ad: ' + thresholdType);
                }
                return defaultThreshold;
            },

            prefetchAd: function() {
                if (!this.subviews.adSlot) {
                    this.subviews.adSlot = AdManager.getAdSlot(this.options.adPlacement, this.options.targeting, this.options.adSizes, this, this.options.slotType);
                }
            },

            tickMeter: function(noAd) {
                var meter,
                    showAd = false,
                    rateMeterId = 'dfpc_' + this.options.rateMeterId,
                    defaultThreshold = this.getDefaultThreshold();
                if (!defaultThreshold) {
                    return showAd;
                }
                meter = App.getSessionData(rateMeterId, defaultThreshold);
                meter[0] = Math.max(0, meter[0] - 1);
                if (meter[0] < 1 && !noAd) {
                    showAd = true;
                    meter[0] = meter[1]; // reset the meter to the next position
                }
                App.setSessionData(rateMeterId, meter);
                return showAd;
            },

            shouldShowAd: function() {
                var showAd = this.tickMeter();
                this.prefetchAd();
                if (showAd && !this.isAdReady) {
                    // ad isn't ready to be shown, skip it and try again
                    AdLogger.logDebug('ad skipped due to no ad being delivered in time, refreshing slot');
                    this.refreshPosition();
                    showAd = false;
                }
                AdLogger.logDebug('shouldShowAd: ' + showAd, this);
                return showAd;
            }
        });
        return MeteredAdPosition;
    });
/**
 * @fileoverview Builds an ad position on the page
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('directAdPosition',[
    'jquery',
    'underscore',
    'views/modules/partner/ad-position',
    'app',
    'admanager',
    'adLogger'
],
    function($, _, AdPosition, App, AdManager, AdLogger) {
        

        var DirectAdPosition = AdPosition.extend({
            /**
             * Initializes the view
             * @param options = { aws, pageName, pageType [ blog, card, cover, media, overlay, topic ], url }
             */
            initialize: function(options) {
                options = $.extend({
                    // required options
                    targeting: {},
                    slotType: 'in' // in page by default
                }, options);

                // call base class initialize
                AdPosition.prototype.initialize.call(this, options);

                if (options.pageInfo) {
                    this.setPageInfo(options.pageInfo);
                }

                this.subviews.adSlot = AdManager.getAdSlot(this.getAdPlacement(), this.options.targeting, this.options.adSizes, this, this.options.slotType);
            },

            setTargeting: function(targeting) {
                this.options.targeting = targeting;
                if (this.subviews.adSlot) {
                    this.subviews.adSlot.setTargeting(this.options.targeting);
                }
            },

            setPageInfo: function(pageInfo){
                this.options.subSection = pageInfo.aws;
                this.setTargeting(AdManager.getPageTargeting(pageInfo));
            },

            refreshPosition: function() {
                this.destroyAdPlacement();
                if (this.subviews.adSlot) {
                    this.subviews.adSlot.refresh();
                }
            }
        });
        return DirectAdPosition;
    });
/**
 * @fileoverview Gallery subview of carousel. In charge of the the stacked images and endslate
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel/gallery',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app',
    'views/modules/taboola',
    'meteredAdPosition',
    'directAdPosition',
    'adLogger'
],
    function(
        $,
        _,
        Backbone,
        BaseView,
        PubSub,
        App,
        Taboola,
        MeteredAdPosition,
        DirectAdPosition,
        AdLogger
    ) {

        /**
         * View class.
         */
        var CarouselGallery = BaseView.extend({

            events: {
                'click .gallery-actions-replay, .gallery-photo': 'nextSlide',
                'click .gallery-related-link': 'taboolaClick'
            },

            selectors: {
                endSlate: '.endslate',
                slides: '.slide:not(.partner-placement)'
            },

            endSlateTemplate: '<% _.each(data, function(item) { '+
                'item.thumbnail[0].url = item.thumbnail[0].url.replace("-4_3_rx512_c680x510.jpg", "-16_9_rx86_c150x84.jpg?35580e2dd9b3eae5e5abdf01549071435bf24c1b"); %>' +
                '<li class="gallery-related-item">' +
                '<a class="gallery-related-link" data-taboola-type="<%= item.type %>" ' +
                    'data-taboola-id="<%= item.id %>" data-taboola-response-id="<%=response_id%>"' +
                    'href="<%= item.url %>">' +
                    '<span class="taboola-image-crop">' +
                    '<img src="<%= item.thumbnail[0].url %>" class="taboola-related-img" alt="" />' +
                    '</span>'+
                    '<%= item.name %>' +
                '</a>' +
                '<span class="gallery-related-date"><%= item.created %></span>' +
                '</li>' +
                '<% }); %>',

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                _.bindAll(this, '_showEndslate');

                options = $.extend({
                    // transition set to 0 to resolve "flash" - Reinstate to 200 to add transition effect
                    ads: true,
                    slideTransition: 0,
                    imageLazySrcAttr: 'data-src',
                    lookAheadAmount: 2 // how many additional photos to fetch
                }, options);

                this.index = options.index;

                // Call base class initialize
                BaseView.prototype.initialize.call(this, options);
                 
                if (options.ads) {
                    this.galleryData = this.$el.data();
                    var targeting = this.getAdTargeting();

                    this.$sponsorshipAd = this.$('.snapshot-sponsor');
                    if (this.$sponsorshipAd.length) {
                        var currentSlideId = this._getSlideIn(this.index).data('qqid');
                        targeting.snapshotid = currentSlideId;
                        this.subviews.sponsorshipAd = new DirectAdPosition({
                            el: this.$sponsorshipAd,
                            adPlacement: 'sponsor_logo/snapshots',
                            adSizes: ['sponsor_logo'],
                            targeting: targeting
                        });
                    }
                    this.$viewport = this.$('.viewport');
                    var viewportWidth = this.$viewport.width(), viewportHeight = this.$viewport.height();
                    if (viewportHeight < 450 || viewportWidth < 600) {
                        AdLogger.logWarn('Advertisement viewport is too small: ' + viewportWidth + 'x' + viewportHeight);
                    } else {
                        this.$adSlide = this.$('.partner-slide-ad');
                        this.$adContents = this.$('.partner-slide-ad .gallery-photo-border');
                        this.setAdSize(viewportWidth, viewportHeight);
                        var meterThreshold = null;
                        if (this.galleryData.galleryId === 'snapshot') {
                            meterThreshold = 'transition_snapshot';
                        }
                        this.subviews.ad = new MeteredAdPosition({
                            el: this.$adContents,
                            adPlacement: 'transition_gallery/' + this.galleryData.cst,
                            adSizes: ['elastic'],
                            meterThreshold: meterThreshold,
                            rateMeterId: 'gallery_' + this.galleryData.galleryId,
                            targeting: targeting
                        });
                    }
                }

                this.endSlateBuilt = false;
            },

            getAdTargeting: function(){
                return {
                    title: this.galleryData.seoTitle,
                    sitePage: 'usat/' + (this.galleryData.ssts || '').replace(/\/\/*$/, ''),
                    series: this.galleryData.series,
                    topic: this.galleryData.topic
                };

            },

            /**
             * post initialize render function that will check to see if a higher rez image needs to be loaded
             */
            render: function(){
                // load the larger sized image if needed
                this._loadImage(this.$$(this.selectors.slides).eq(this.index));
            },

            /**
             * Event callback
             * @param {Event} e
             */
            taboolaClick: function(e){
                var img = $(e.currentTarget);

                Taboola.prototype.registerTaboolaClick(img.attr('data-taboola-id'),
                                                        img.attr('data-taboola-type'),
                                                        img.attr('data-taboola-response-id'),
                                                        'end-slate');
            },

            /**
             * Event callback to navigate to the next slide
             * @param {Event} e click event
             */
            nextSlide: function(e){
                e.preventDefault();
                this.options.carousel.switchSlide(null, 1);
            },

            /**
             * Make call to Taboola to build the end slate, add loading class
             * Will register the _showEndSlate callback with Taboola to render and cleanup
             * @private
             */
            _buildEndslate: function() {
                this.endSlateBuilt = true;

                // Make request to taboola to get recommended videos.
                var url = window.location.href;
                if (this.$el.hasClass('hasendslate') && this.$el.data('gallery-id')) {
                    url = window.location.protocol + '//' + window.location.host + '/picture-gallery/' + this.$el.data('gallery-id') + '/';
                }
                var taboola = new Taboola();
                this.$$(this.selectors.endSlate).addClass('loading');
                taboola.getRelated(this._showEndslate, 'photo', 'photo', 4, url, this.$el.data('gallery-id'));
            },

            /**
             * Taboola callback that will render the related items list for the end slate and remove the loading class
             * @param {Object} data Taboola data
             * @private
             */
            _showEndslate: function(data) {
                var endslate = this.$$(this.selectors.endSlate).removeClass('loading');
                if (endslate.length === 1) {
                    var compiled = _.template(this.endSlateTemplate, {data: data.list, response_id: data.id});
                    endslate.find('.gallery-endslate-related').html(compiled);
                }
            },

            /**
             * Event listener that will transition from the current index to the next index
             * @param {Number} index slide index to go to
             * @return {Deferred}
             */
            goToSlide: function(index){
                // must happen before slideIn, cause slideIn might pick an ad
                var slideOut = this._getSlideOut();
                var slideIn = this._getSlideIn(index);

                if (!slideIn.length){
                    // guard to prevent a crash in switchSlides
                    return $.Deferred().reject();
                }

                this.index = index;

                PubSub.trigger('carousel:switchSlide');

                return this._switchSlides(slideIn, slideOut, this.options.slideTransition);
            },

            /**
             * Asks the gallery whether the next slide should be an ad
             * @return {Boolean}
             */
            shouldShowAd: function(){
                if (!this.showingAd && this.options.ads && this.subviews.ad && this.subviews.ad.shouldShowAd()){
                    return true;
                }
                return false;
            },

            /**
             * Will fadeOut out the current slide and fadeIn the current ad
             * @return {Deferred}
             */
            showAd: function(){
                var slideOut = this._getSlideOut();
                this.showingAd = this.$adSlide;
                if (slideOut[0] !== this.showingAd[0]){
                    if (this.$sponsorshipAd) {
                        this.$sponsorshipAd.hide();
                    }
                    return this._switchSlides(this.showingAd, slideOut, this.options.slideTransition).done(_.bind(function(){
                        this.subviews.ad.playAd();
                    }, this));
                }else{
                    return $.Deferred().reject();
                }
            },

            /**
             * Takes a target slide and a current slide and cross fades them
             * @param {jQuery} slideIn slide to fade in
             * @param {jQuery} slideOut slide to fade out
             * @param {Integer} transitionTime time in ms to transition
             * @return {Deferred}
             * @private
             */
            _switchSlides: function(slideIn, slideOut, transitionTime){
                var deferred = $.Deferred();
                slideOut.css({opacity: 1});
                if (slideOut === this.showingAd){
                    this.subviews.ad.stopAd();
                }
                this.animate(slideOut, 'opacity', 0, transitionTime, 'ease-in-out').done(_.bind(function(){
                    slideOut.removeClass('active');
                    if (slideOut === this.showingAd){
                        this.subviews.ad.refreshPosition();
                        this.showingAd = null;
                    }
                    this._fadeInSlide(slideIn, transitionTime).done(_.bind(function(){
                        if (slideIn !== this.showingAd && this.$sponsorshipAd && this.$sponsorshipAd.length) {
                            this.refreshSponsorshipAd(slideIn.data('qqid'));
                        }
                        slideOut.css({visibility: 'hidden', opacity: 0});
                        deferred.resolve();
                    }, this));
                }, this));
                return deferred.promise();
            },

            /**
             * Given a snapshot id, will reset the targeting of the snapshot ad and refresh it
             * @param {Number} snapshotId the id of the current snapshot
            */
            refreshSponsorshipAd: function(snapshotId){
                var targeting = this.getAdTargeting();
                targeting.snapshotid = snapshotId;
                this.subviews.sponsorshipAd.setTargeting(targeting);
                this.subviews.sponsorshipAd.refreshPosition();
            },

            /**
             * Determines the active slide or ad that needs to fade out
             * @return {jQuery}
             * @private
             */
            _getSlideOut: function(){
                var slideOut;
                if (this.showingAd){
                    slideOut = this.showingAd;
                }else{
                    slideOut = this.$$(this.selectors.slides).eq(this.index);
                }
                return slideOut;
            },
            /**
             * Gets the slide to fade in, loads any images that need to be loaded
             * @param index index of the slide to load in, assumes it's a valid index
             * @return {jQuery}
             * @private
             */
            _getSlideIn: function(index){
                var slideIn;
                slideIn = this.$$(this.selectors.slides).eq(index);
                this._loadImage(slideIn, this.index > index);
                if (!this.endSlateBuilt && slideIn.hasClass('endslate')){
                    this._buildEndslate();
                }
                return slideIn;
            },
            /**
             * given a slide, will load it's image if needed,
             * and the next X images specified by this.options.lookAheadAmount
             * @param {jQuery} slide
             * @param {Boolean} backward specifying if we're traversing backwards or forward
             * @private
             */
            _loadImage: function(slide, backward){
                var i = this.options.lookAheadAmount;
                do{
                    this._fetchImage(slide.find("img"));
                    i--;
                    if (backward){
                        slide = slide.prev();
                    }else{
                        slide = slide.next();
                    }
                } while (i >= 0 && slide.length > 0);
            },
            /**
             * Fetches one lazy image, hides the image until loading,
             * adds a loading class, restores everything on load
             * @param {jQuery} img to load
             * @private
             */
            _fetchImage: function(img){
                if (img.length > 0) {
                    if (App.lazyLoadImage(img, this.options.imageLazySrcAttr)) {
                        // we're lazily loading, add loading class
                        var parent = img.parent();
                        parent.addClass("loading");
                        img.load(_.bind(function() {
                            parent.removeClass("loading");
                            this._resizeMeta(img);
                        }, this));
                    }
                }
            },

            /**
             * Takes a slide, makes it visible, gives it an active class, and animates in it's opacity
             * also resizes the meta tag to fit the image
             * @param {jQuery} slide to fade in
             * @param {Integer} transitionTime time in ms to animate
             * @return {Deferred}
             * @private
             */
            _fadeInSlide: function(slide, transitionTime){
                slide.css({visibility: 'visible', 'z-index': 1});
                slide.addClass('active');
                this._resizeMeta(slide.find('.gallery-photo'));
                return this.animate(slide, 'opacity', 1, transitionTime, 'ease-in-out');
            },

            /**
             * helper function to get the current image width and size the metadata to fix exactly
             * that size in width
             * @param {jQuery} img
             * @private
             */
            _resizeMeta: function(img){
                if (img.length){
                    var width = this._getImageWidth(img);
                    // hidden images return 0 width, it's better at that point to let the browser auto size
                    if (width){
                        img.parent().width(width);
                    }
                }
            },

            /**
             * Silly function to help unit test
             * @param {jQuery} img to be sized
             * @return {Number} width of the image
             * @private
             */
            _getImageWidth: function(img){
                return img.width();
            },

            /**
             * carousel callback that is triggered on viewport resize so we can resize the active image's meta width
             * @param {Number} width viewport width
             * @param {Number} height viewport height
             */
            viewportResize: function(width, height) {
                // resize the active photo
                this.$('.active .gallery-photo').each(_.bind(function(idx, img){
                    this._resizeMeta($(img));
                }, this));
                if (this.$adSlide && this.subviews.ad) {
                    this.setAdSize(width, height);
                    this.subviews.ad.resizeAd(width, height);
                }
            },

            /**
             * sets the correct ad size. We need this since the photo border by default wraps the
             * contents, but ads are auto sizing, so someone needs to man up and define a size
             * @param {Number} width
             * @param {Number} height
             */
            setAdSize: function(width, height){
                var adSizing = this.findSizeForAd(width, height);
                this.$adContents.removeClass('size-s size-m size-l size-xl').addClass(adSizing.adSizeClass).css('margin-top', adSizing.marginTop);
            },

            /**
             * Magic number finder, given combinations of heights and widths figures out an appropriate ad size
             * @param {Number} ww viewport Width
             * @param {Number} wh viewport Height
             */
            findSizeForAd: function(ww, wh) {
                var obj = {
                    'adSizeClass' : 'size-s',
                    'marginTop' : '5px'
                };
                // check size
                var h = 450;
                if (ww > 1080 && wh > 810) {
                    obj.adSizeClass = 'size-xl';
                    h = 810;
                } else if (ww > 936 && wh > 700) {
                    obj.adSizeClass = 'size-l';
                    h = 700;
                } else if (ww > 768 && wh > 576) {
                    obj.adSizeClass = 'size-m';
                    h = 576;
                }

                obj.marginTop = ((wh - h) / 2) + 'px';

                // default to small
                return obj;
            }
        });
        return CarouselGallery;
    }
);
/**
 * @fileoverview Controls subview of carousel. In charge of the next/prev arrows, buttons, widgets, autoplay
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel/controls',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app'
],
    function(
        $,
        _,
        Backbone,
        BaseView,
        PubSub
    ) {
        var CarouselControls = BaseView.extend({

            events: {
                'click .slide-nav': 'switchSlide',
                'click .autoplay': 'autoplay',
                'click .thumbnails': 'thumbsToggle',
                'click .captions': 'captionsToggle',
                'mouseenter': 'mouseover',
                'mouseleave' : 'mouseout',
                'click .fullscreen': 'launchFullscreen'
            },

            selectors: {
                allCaptions: '.meta',
                captionBtnLabel: '.captionLabel',
                nextArrow: '.slide-nav.next',
                playBtn: '.playbtn',
                prevArrow: '.slide-nav.prev',
                thumbsBtnLabel: '.thumbLabel',
                thumbsWrapper: '.thumbs',
                ticker: '.ticker',
                viewport: '.viewport'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {

                options = $.extend({
                    index: 0,
                    hoverShowControls: true,
                    interactionDemo: true,
                    interactionShowDelay: 600, // ms
                    interactionHideDelay: 3600, // ms
                    totalImages: 0,
                    totalSlides: 0
                }, options);

                this.index = options.index;

                // Call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },

            /**
             * post initialize render function. Updates ticker, updates Next/Prev Arrows
             * starts interaction demo if the option is provided
             */
            render: function(){
                this.updateTicker();
                this.updateNextPrevArrows(this.index);
                if (this.options.interactionDemo){
                    // don't start the interaction demo in full screen since it's hard to stop it from
                    // happening since it's based on mouseovers that might not fire
                    this.startInteractionDemo();
                }
            },

            destroy: function(removeEl){
                this.clearUserInteractionDemo();
                BaseView.prototype.destroy.call(this, removeEl);
            },

            /**
             * Event callback on next/prev slide-nav.
             * Will trigger carousel to switch 1 forward or one back
             * @param e
             */
            switchSlide: function(e){
                e.preventDefault();
                if ($(e.currentTarget).hasClass('prev')){
                    this.options.carousel.switchSlide(null, -1);
                }else{
                    this.options.carousel.switchSlide(null, 1);
                }
            },

            /**
             * Event callback that turns on or off autoplay (all controled by carousel)
             * @param e
             */
            autoplay: function(e) {
                e.preventDefault();
                // auto play just notifies the carousel to change it's state
                // the carousel itself controls the start/stop logic of the autoplay and associated event calling
                this.options.carousel.autoplay();
            },

            /**
             * Starts timers to initially expose next/prev navigation.
             */
            startInteractionDemo: function() {
                var _this = this;
                this.uxTimeout1 = setTimeout(function() {
                    _this.$el.addClass('hover');
                }, this.options.interactionShowDelay);

                this.uxTimeout2 = setTimeout(function() {
                    _this.$el.removeClass('hover');
                }, this.options.interactionHideDelay);
            },

            /**
             * Stops interaction timers
             */
            clearUserInteractionDemo: function(){
                clearTimeout(this.uxTimeout1);
                clearTimeout(this.uxTimeout2);
            },

            /**
             * Mouseover handler for the carousel
             * - will add hover class to this.$el
             * - will add hover class to the viewport if hoverShowControls = true
             * - clears user interaction demo so the user's experience isn't interrupted
             */
            mouseover: function(){
                if (this.options.hoverShowControls){
                    this.$$(this.selectors.viewport).addClass('hover');
                }
                this.$el.addClass('hover');
                this.clearUserInteractionDemo();
            },

            /**
             * Mouseout handler for the carousel
             * - will remove hover class on this.$el
             * - will remove hover class on the viewport if hoverShowControls = true
             */
            mouseout: function(){
                if (this.options.hoverShowControls){
                    this.$$(this.selectors.viewport).removeClass('hover');
                }
                this.$el.removeClass('hover');
            },

            /**
             * Launch fullscreen view
             * @param {Event} e View click event.
             */
            launchFullscreen: function(e) {
                e.preventDefault();

                // need PubSub to break circular dependency
                PubSub.trigger('openFullScreenCarousel', {
                    carousel: this,
                    fullScreen: true,
                    parent: this.$el
                });
            },

            /**
             * Toggle on/off captions, updates button label
             * @param {Event} e Browser event.
             */
            captionsToggle: function(e) {
                var meta = this.$$(this.selectors.allCaptions),
                    label = this.$$(this.selectors.captionBtnLabel);

                e.preventDefault();
                if (meta.hasClass('on')) {
                    meta.removeClass('on');
                    label.html('Show Captions');
                } else {
                    meta.addClass('on');
                    label.html('Hide Captions');
                }
            },

            /**
             * Toggle on/off thumbnails, updates button label
             * @param {Event} e Browser event.
             */
            thumbsToggle: function(e) {
                var label = this.$$(this.selectors.thumbsBtnLabel),
                    thumbs = this.$$(this.selectors.thumbsWrapper);

                e.preventDefault();
                if (thumbs.hasClass('on')) {
                    thumbs.removeClass('on');
                    label.html('Show Thumbnails');
                    this.options.carousel.toggleThumbnail(false);
                } else {
                    thumbs.addClass('on');
                    label.html('Hide Thumbnails');
                    this.options.carousel.toggleThumbnail(true);
                }
            },

            /**
             * shows and hides the next/prev arrows based on the index provided
             * @param {Integer} index
             */
            updateNextPrevArrows: function(index){
                var $prevArrow = this.$$(this.selectors.prevArrow),
                    $nextArrow = this.$$(this.selectors.nextArrow);
                if (index === 0) {
                    $prevArrow.hide();
                }else{
                    $prevArrow.show();
                }
                if (index < (this.options.totalSlides - 1)){
                    $nextArrow.show();
                }else{
                    $nextArrow.hide();
                }
            },

            /**
             * Update slide ticker html (Image 1 of 9).
             */
            updateTicker: function() {
                // Get the details of what we're setting.
                var $ticker = this.$$(this.selectors.ticker);

                if ($ticker.length){
                    if (this.index < this.options.totalImages){
                        $ticker.css({'visibility': 'visible'});
                    }else{
                        // we set visibility to keep the other icons in line
                        $ticker.css({'visibility': 'hidden'});
                    }
                    $ticker.html('<b>' + (this.index + 1) + '</b> of <b>' + this.options.totalImages + '</b>');
                }
            },

            /**
             * Go to slide event callback from carousel, will update next/prev arrows and ticker
             * @param index
             */
            goToSlide: function(index){
                this.index = index;
                this.updateNextPrevArrows(index);
                this.updateTicker();
            },

            /**
             * onPlay event callback from carousel
             * will change playButton text to 'Pause' and add a 'pause' class
             */
            onPlay: function(){
                this.$$(this.selectors.playBtn).addClass('pause').text('Pause');
            },

            /**
             * onStop event callback from carousel
             * will change playButton text to 'Autoplay' and remove 'pause' class
             */
            onStop: function(){
                this.$$(this.selectors.playBtn).removeClass('pause').text('Autoplay');
            }

        });
        return CarouselControls;
    }
);
/**
 * @fileoverview HorizontalScroll view module.
 * 
 * When instantiating the class pass and object that defines:
 * el: The container of the scrollable content and where the scrollbar will be placed
 * contentClass: The class name that the scrollable content div has (this class must sit
 * within the container)
 * template: markup for the actual scroller
 * padding: left/right padding amount for the scroller
 * To use outside gallery thumbs set an alternate el and contentClass when instantiating
 * the class. Any issues / questions don't hesitate to contact me.
 *
 * SEE BASE-SCROLL.JS FOR TROUBLESHOOTING ADVICE
 * 
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
 define('views/modules/scroller/horizontal-scroll',[
    'jquery', 
    'underscore', 
    'views/modules/scroller/base-scroll'
],
function(
    $, 
    _, 
    BaseScroll
)
    {

        /**
         * View class.
         */
        var HorizontalScrollView = BaseScroll.extend({

            /**
             * Initialize view.
             */
            initialize: function(options) {

                options = $.extend({
                    color: 'light', // light or dark
                    draggerPaddingLeft: 0,
                    draggerPaddingRight: 2,
                    delayScroll: true
                }, options);

                // Set up html template based on color.
                var compiled = _.template('<div class="horizontal-scroll ui-<%= color %>"><div class="scrolldragger"><div class="over-icon"></div></div></div>');
                options.template = compiled({color: options.color});

                // Remove any pre-existing instances just in case.
                this.$('.horizontal-scroll').remove();

                BaseScroll.prototype.initialize.call(this, options);
            },

            destroy: function(removeEl){
                // Call base class destroy
                BaseScroll.prototype.destroy.call(this, removeEl);
            },

            getViewportSize: function(){
                return this.$el.width();
            },
            getContentSize: function(){
                return this.content.width();
            },
            _setDraggerSize: function(draggerSize){
                draggerSize -= (this.options.draggerPaddingLeft + this.options.draggerPaddingRight);
                this.dragger.css({width: draggerSize});
                return draggerSize;
            },

            animateContentToPosition: function(locationX, locationY, duration, easing){
                var minPosition = this.viewportSize - this.contentSize,
                    actualLocationX = Math.max(minPosition, Math.min(locationX, 0));
                easing = easing || 'ease-out';
                $.when(this.animate(this.dragger, 'left', (-1 * actualLocationX * this.contentViewportRatio) + 'px', duration || 0, easing),
                        this.animate(this.content, 'left', actualLocationX + 'px', duration, easing))
                    .done(_.bind(function(){
                        this.$el.trigger('scrollBarUpdate', [actualLocationX / minPosition]);
                    }, this));
            },

            /**
             * will scroll to make the element visible
             * @param {jQuery} item html element that we want to be visible
             * @param {Boolean} pageJump specifies if we're moving the viewport a full page, or just one line
             * @param {Number} duration time for animation
             * @param {String} [easing] easing formula
             */
            scrollToElement: function(item, pageJump, duration, easing) {
                var shift, itemWidth = item.outerWidth(),
                    itemLeftPosition = item.position().left + item.parent().position().left,
                    itemRightPosition = itemLeftPosition + itemWidth;
                if (itemLeftPosition < 0) {
                    var viewportSize = this.getViewportSize();
                    if (pageJump) {
                        shift = itemLeftPosition + (itemWidth - viewportSize);
                    } else {
                        shift = itemLeftPosition;
                    }
                } else if (itemRightPosition > this.getViewportSize()) {
                    if (pageJump) {
                        shift = itemLeftPosition;
                    } else {
                        shift = itemLeftPosition + (itemWidth - this.getViewportSize());
                    }
                }
                if (shift) {
                    var finalPosition = this.content.position().left - shift;
                    this.animateContentToPosition(finalPosition, 0, duration, easing);
                }
            },

            moveContentToPosition: function(locationX, locationY){
                if (!this.active){
                    return false;
                }
                var minPosition = this.viewportSize - this.contentSize,
                    actualLocationX = Math.max(minPosition, Math.min(locationX, 0));
                this._positionDragger(-1 * actualLocationX * this.contentViewportRatio);
                this._positionContent(actualLocationX);
                this.$el.trigger('scrollBarUpdate', [actualLocationX / minPosition]);
                return actualLocationX === locationX;
            },

            moveDraggerToPosition: function(locationX, locationY){
                if (!this.active){
                    return false;
                }
                var maxPosition = this.viewportSize - (this.draggerSize + this.options.draggerPaddingRight + this.options.draggerPaddingLeft),
                    actualLocationX = Math.max(0, Math.min(locationX, maxPosition));
                this._positionDragger(actualLocationX);
                this._positionContent(-1 * actualLocationX / this.contentViewportRatio);
                this.$el.trigger('scrollBarUpdate', actualLocationX / maxPosition);
                return actualLocationX === locationX;
            },
            _positionDragger: function(x){
                x += this.options.draggerPaddingLeft;
                x = Math.round(x);
                if (this.useCSSTransforms){
                    this.dragger.css({left: '0'});
                    this.dragger[0].style[this.transformCssName] = 'translate(' + x + 'px,0)';
                }else{
                    this.dragger.css({left: x});
                }
            },
            _positionContent: function(x){
                x = Math.round(x);
                if (this.useCSSTransforms){
                    this.content.css({left: '0'});
                    this.content[0].style[this.transformCssName] = 'translate(' + x + 'px,0)';
                }else{
                    this.content.css({left: x});
                }
            }

        });


        /**
         * Return view class.
         */
        return HorizontalScrollView;
    }
);

/**
 * @fileoverview Thumbs subview of carousel. Handles rendering of the thumbs, clicking of the thumbs
 * and the hover transition over thumbs if turned on
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel/thumbs',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app',
    'views/modules/scroller/horizontal-scroll'
],
    function(
        $,
        _,
        Backbone,
        BaseView,
        PubSub,
        App,
        HorizontalScroll
    ) {

        /**
         * View class.
         */
        var CarouselThumbs = BaseView.extend({

            events: {
                'mouseenter li' : 'thumbMouseover',
                'mouseleave li' : 'thumbMouseout',
                'click li' : 'switchSlide'
            },

            selectors: {
                thumbs: 'li'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                options = $.extend({
                    // setting the hoverTransition to 0 will disable hover transition, any other value
                    // will delay that many ms and switch to that slide
                    hoverTransition: 0
                }, options);

                this.index = options.index;

                // Call base class initialize
                BaseView.prototype.initialize.call(this, options);

                // Initialize the horizontal scroll
                this.subviews.scrollbar = new HorizontalScroll({
                    el: this.$el,
                    color: this.options.scrollerColor,
                    padding: 2
                });
            },

            destroy: function(removeEl) {
                // Call base class destroy
                BaseView.prototype.destroy.call(this, removeEl);
            },

            /**
             * Event callback on thumbs that will trigger switching to that thumb's index
             * @param e
             */
            switchSlide: function(e){
                e.preventDefault();
                var clickIndex = $(e.currentTarget).index();
                this.options.carousel.switchSlide(clickIndex);
            },

            /**
             * Function that is triggered when an ad is being shown, will remove the active class of the current thumb
             */
            showAd: function(){
                var $thumbs = this.$$(this.selectors.thumbs);
                $thumbs.eq(this.index).removeClass('active');
            },

            /**
             * Event callback on mouse over on thumbs, used when hoverTransition is on, will
             * switch to that slide after a specified amount of time (this.options.hoverTransition)
             * @param event
             */
            thumbMouseover: function(event) {
                var target = event.currentTarget;
                if (this.options.hoverTransition) {
                    this.hoverTimeout = setTimeout(_.bind(function() {
                        this.hoverTimeout = null;
                        // don't track the hover transition because it's only used on heros
                        // which don't have the right attributes for the data track
                        this.options.carousel.switchSlide($(target).index(), null, true);
                    }, this), this.options.hoverTransition);
                }
            },

            /**
             * Event callback on mouse out on thumbs, will clear the hover timeout if it's still active
             * @param event
             */
            thumbMouseout: function(event) {
                if (this.options.hoverTransition) {
                    if (this.hoverTimeout) {
                        clearTimeout(this.hoverTimeout);
                    }
                }
            },

            /**
             * Function that will remove the current index's 'active' class and add 'active'
             * to the given index
             * @param index
             */
            goToSlide: function(index){
                var $thumbs = this.$$(this.selectors.thumbs),
                    $targetThumb = $thumbs.eq(index);
                $thumbs.eq(this.index).removeClass('active');
                $targetThumb.addClass('active');
                this.index = index;
                this.subviews.scrollbar.scrollToElement($targetThumb, false, 300);
            },

            /**
             * carousel callback triggered on viewport size changed,
             * allows us to update the thumbnail scrollbar
             */
            viewportResize: function(){
                if (this.subviews.scrollbar){
                    this.subviews.scrollbar.refresh();
                }
            }

        });

        return CarouselThumbs;
    }
);
/**
 * @fileoverview Global carousel module view.
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'app',
    'views/modules/carousel/gallery',
    'views/modules/carousel/controls',
    'views/modules/carousel/thumbs'
    ],
    function(
        $,
        _,
        Backbone,
        BaseView,
        PubSub,
        App,
        CarouselGallery,
        CarouselControls,
        CarouselThumbs
    ) {

        /**
         * View class.
         */
        var CarouselView = BaseView.extend({

            events: {
                mouseenter: 'mouseEnter'
            },

            selectors: {
                slides: '.slide:not(.partner-placement)',
                images: '.slide:not(.partner-placement,.endslate)'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                options = $.extend({
                    ads: true,
                    // transition set to 0 to resolve "flash" - Reinstate to 200 to add transition effect
                    slideTransition: 0,
                    hoverShowControls: true,
                    hoverTransition: 0, // if set to non-zero, will cause hovering over thumbs to switch to that slide
                    interactionDemo: true,
                    linkPath: null, // the path to the gallery (used for ads)
                    rotate: false,
                    controlsSelector: null, // by default selector is this.$el
                    gallerySelector: null, // by default selector is this.$el
                    thumbsSelector: '.thumbs',
                    imageLazySrcAttr: 'data-src',
                    scrollerColor: 'light',
                    rotateInterval: 3000,
                    autostart: false
                }, options);

                _.bindAll(this, 'rotateCarousel');

                this.index = this.$('.slide.active').index();
                if (this.index === -1){
                    this.index = 0;
                }

                this.linkPath =  options.linkPath? options.linkPath : '';
                //Tracking on hold for FW
                //this.tracking = (options.track) ? options.track : false;
                this.playTimer = null;

                this.subviews = {};

                // All initialization functions assume that this.index has been set
                this._initializeGallery(options.imageLazySrcAttr, options.slideTransition, options.ads, options.gallerySelector);
                this._initializeControls(options.hoverShowControls, options.interactionDemo, options.controlsSelector);
                this._initializeThumbs(options.hoverTransition, options.scrollerColor, options.thumbsSelector);

                // Listen for pause from hero flip ad
                this.pubSub = {
                    'carousel:stoptimer': this.stoptimer,
                    'carousel:starttimer': this.resumeAutoPlay
                };

                // Call base class initialize
                BaseView.prototype.initialize.call(this, options);

                if (options.autostart) {
                    this._startCarouselRotate();
                }
            },

            _initializeGallery: function(imageLazySrcAttr, slideTransition, showAds, selector){
                this.subviews.gallery = new CarouselGallery({
                    ads: showAds,
                    el: (selector ? this.$(selector) : this.$el),
                    index: this.index,
                    imageLazySrcAttr: imageLazySrcAttr,
                    slideTransition: slideTransition,
                    carousel: this
                });
            },

            _initializeControls: function(hoverShowControls, interactionDemo, selector) {
                var images = this.$(this.selectors.images);
                var slides = this.$$(this.selectors.slides);
                this.subviews.controls = new CarouselControls({
                    el: (selector ? this.$(selector) : this.$el),
                    hoverShowControls: hoverShowControls,
                    interactionDemo: interactionDemo,
                    index: this.index,
                    totalSlides: slides.length,
                    totalImages: images.length,
                    carousel: this
                });
                this.subviews.controls.render();
            },

            _initializeThumbs: function(hoverTransition, scrollerColor, selector) {
                this.subviews.thumbs = new CarouselThumbs({
                    el: (selector ? this.$(selector) : this.$el),
                    hoverTransition: hoverTransition,
                    index: this.index,
                    scrollerColor: scrollerColor,
                    carousel: this
                });
            },

            mouseEnter: function(){
                if (this.options.autostart){
                    this._stopCarouselRotate();
                }
            },

            /*
             * Function to handle automated rotation of the carousel.
             */
            rotateCarousel: function() {
                // Get the details of what we're automating.
                var numberOfItems = this.$$(this.selectors.slides).length - 1;

                this.switchSlide(null, 1, true);
                if (this.index === numberOfItems && !this.options.rotate){
                    // stop rotation when we hit the end
                    this._stopCarouselRotate();
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                if (this.playTimer) {
                    this._stopCarouselRotate();
                }
                // Call base class destroy
                BaseView.prototype.destroy.call(this, removeEl);
            },

            /*
             * Stop the interval - primarily used when hovering the module and hero flip
             */
            stoptimer: function() {
                clearInterval(this.playTimer);
                this.playTimer = null;
            },

            /*
             * Switch from one slide to another.
             * @param {Number} index position to move the carousel to.
             * @param {Number} slideOffset offset from current index to go to, this takes precidence over index position.
             * @param {Boolean} [noTrack] variable to specify whether the event was generated from an auto rotator
             */
            switchSlide: function(index, slideOffset, noTrack) {
                var numSlides = this.$$(this.selectors.slides).length;

                if (!this.showingAd && this.subviews.gallery.shouldShowAd()){
                    this.showingAd = true;
                    this.slideAdStep = slideOffset;
                    this.triggerEvent('showAd');
                    return;
                }

                if (slideOffset) {
                    if (this.slideAdStep && this.slideAdStep !== slideOffset){
                        // we've changed direction, pretend like we actually succeeded in the last slide offset
                        slideOffset += this.slideAdStep;
                    }
                    var newIndex = this.index + slideOffset;
                    if (newIndex < 0){
                        index = numSlides - 1;
                    }else if (newIndex >= numSlides){
                        index = 0;
                    }else{
                        index = newIndex;
                    }
                }else if (index < 0){
                    index = 0;
                }else if (index >= numSlides){
                    index = numSlides - 1;
                }

                if (this.index === index && !this.showingAd) {
                    return;
                }
                this.showingAd = false;
                this.slideAdStep = 0;
                this.index = index;
                this.triggerEvent('goToSlide', index);

                if (!noTrack) {
                    this._trackSlideChange();
                }
            },

            _trackSlideChange: function() { 
                var $el;
                if (this.$el.hasClass('galleries')){
                    $el = this.$el;
                }else{
                    $el = this.$('.galleries');
                }
                // hero galleries get their layout name instead of gallery id as they do not have an id
                var galleryID = $el.attr('data-gallery-id');
                // embedded galleries get thier path name from the markup. 
                var gallerypathname = ($el.attr('data-gal-pageurl') ||"").replace(/^.*\/\/[^\/]+/, '');
                //gallery info object
                var galleryInfObj = {
                    'gallery_id': galleryID,
                    'gallery_title': $el.attr('data-title'),
                    'gallery_index': this.index+1,
                    'slide_id': $el.find('.slide.active img').attr('data-id'),
                    'ssts': $el.attr('data-ssts'),
                    'cst': ($el.attr('data-cst') || 'bugpages').replace(/\/+$/, ""),
                    'contenttype': ('snapshot' === galleryID ? 'snapshot' :'galleries'),
                    'pathName':(gallerypathname ==="")? this.linkPath :gallerypathname
                };
                PubSub.trigger('slide:change', galleryInfObj);
                /*  COMSCORE custom tracking request  */
                $.ajax({url: "/static/html/comscorepvcandidate.xml", cache: false});
            },

            /**
             * Start autoplay.
             */
            autoplay: function() {
                if (this.playTimer) {
                    this._stopCarouselRotate();
                } else {
                    this._startCarouselRotate(true);
                }
            },

            /**
             * Starts the autoplay rotate
             * @private
             */
            _startCarouselRotate: function(advanceImmediately){
                // switchSlide will call autostart again for the next transition
                this.playTimer = setInterval(this.rotateCarousel, this.options.rotateInterval);
                if (advanceImmediately){
                    this.rotateCarousel();
                }
                this.triggerEvent('onPlay');
            },

            /**
             * Stops autoplay rotate.
             * @private
             */
            _stopCarouselRotate: function() {
                this.stoptimer();
                this.options.autostart = false;
                this.triggerEvent('onStop');
            },

            resumeAutoPlay: function(){
                if (this.options.autostart && !this.playTimer){
                    this._startCarouselRotate();
                }
            },

            /**
             * called when thumbnails are shown or hidden, used by autosize carousel to change the viewport size
             * @param {Boolean} on indicating whether the thumbnails are being turned on or off
             */
            toggleThumbnail: function(on){
                this.triggerEvent('viewportResize');
            }
        });


        /**
         * Return view class.
         */
        return CarouselView;
    }
);

/**
 * @fileoverview Autosizing carousel. This is an extension of Carousel that attachs a window resize
 * handler that will cause the carousel to fill the window (with horizontal and vertical margins)
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel/carousel-autosize',['jquery', 'underscore', 'backbone', 'baseview', 'app', 'views/modules/carousel'],
function($, _, Backbone, BaseView, App, Carousel) {
    /**
     * View class.
     */
    var AutoSizeGallery = Carousel.extend({

        /**
         * Initialize view.
         * @param {Object} options View options passed in during init.
         */
        initialize: function(options) {
            _.bindAll(this, 'handleResizeWindow');

            this.options = $.extend({
                hoverShowControls: false,
                verticalAdjust: 80,
                interactionDemo: false,
                horizontalAdjust: 0,
                thumbSize: 84,
                imageLazySrcAttr: 'data-large-src'
            }, options);

            this.$win = App.get('win');

            if (this.$el.hasClass('galleries')){
                this.$el.addClass('autosize');
            }else{
                this.$('.galleries').addClass('autosize');
            }

            var throttledResize = _.throttle(this.handleResizeWindow, 50);
            this.$win.on('resize.' + this.cid, throttledResize);
            this.handleResizeWindow();

            // call base class initialize
            Carousel.prototype.initialize.call(this, this.options);

            // triggers the updating of the image with the correctly sized one
            this.subviews.gallery.render();
        },

        /**
         * Clean up view.
         * @param {boolean} removeEl option to also remove View from DOM.
         */
        destroy: function(removeEl) {
            this.$win.off('.' + this.cid);

            // call base class destroy
            Carousel.prototype.destroy.call(this, removeEl);
        },

        handleResizeWindow: function(){
            this.windowHeight = this.$win.height();
            this.windowWidth = this.$win.width();

            this.viewportResize();
        },

        viewportResize: function(){
            var galleryheight = this.windowHeight - this.options.verticalAdjust;
            if (this.showThumbs){
                galleryheight -= this.options.thumbSize;
            }
            this.$$('.viewport').height(galleryheight);

            this.triggerEvent('viewportResize', this.windowWidth, galleryheight);
        },

        /**
         * event callback when thumbnails are toggled on and off
         * @override
         * @param on
         */
        toggleThumbnail: function(on){
            this.showThumbs = on;
            this.viewportResize();
        }

    });
    return AutoSizeGallery;
});
/**
 * @fileoverview Fullscreen carousel. This is an extension of carousel-autosize that will copy
 * an existing carousel into a full screen shell with close button and takeover of the current
 * view
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/carousel/carousel-fullscreen',['jquery', 'exports', 'underscore', 'backbone', 'baseview', 'app', 'state', 'views/modules/carousel/carousel-autosize'],
    function($, exports, _, Backbone, BaseView, App, StateManager, CarouselAutoSize) {
        var FullScreenCarousel = CarouselAutoSize.extend({

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                _.bindAll(this, 'handleKeyPress', 'close');

                options = $.extend({
                    scrollerColor: 'dark'
                }, options);

                this.$body = App.get('body');
                this.$doc = App.get('document');
                this.carousel = options.carousel;
                this.parent = options.parent;
                StateManager.registerFullScreenView(this);
                this.$doc.on('keydown.' + this.cid, this.handleKeyPress);
                // sadly, we can't use $el because the $el needs to be the inner gallery for the analytics in carousel to work
                this.$body.on('click.' + this.cid, '.close', this.close);

                this.launch();

                // call base class initialize
                CarouselAutoSize.prototype.initialize.call(this, options);
            },

            /**
             * Close Full Screen Experience.
             * @param {Event} e Browser event.
             */
            close: function(e) {
                if (e) e.preventDefault();
                this.animate(this.$el.parent(), 'opacity', 0, 300, 'ease-in-out').done(_.bind(function(){
                    this.destroy(true);
                    StateManager.clearFullScreenView().done(_.bind(function(){
                        // this click handler has to happen in here because clearFullScreenView will restore the click
                        // handlers of the original carousel
                        if (this.carousel) {
                            // click the original image so the user goes back to the same image they were looking at
                            var $thumbs = $('.thumbs li', this.parent);
                            $thumbs.eq(this.index).click();
                        }
                    }, this));
                }, this));
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.$doc.off('.' + this.cid);
                this.$body.off('.' + this.cid);

                if (removeEl){
                    this.$el.parent().remove();
                }

                // call base class destroy
                CarouselAutoSize.prototype.destroy.call(this, false);
            },

            /**
             * Launch Full Screen Experience.
             */
            launch: function() {
                var html = $('<article class="gallery fullscreen" style="opacity: 0">' +
                    '<a class="close" href="#"></a>' +
                    '<div class="film fullscreen"></div></article>');
                var parentGallery = this.parent.clone();
                parentGallery.find('.viewport').removeClass('hover');
                var pp = parentGallery.find('.partner-placement');
                if (pp.length){
                    var ppId = pp.attr('id') + '_fs';
                    pp.attr('id', ppId).attr('data-slot-id', ppId);
                }
                html.append(parentGallery);
                this.$body.append(html);
                this.animate(html, 'opacity', 1, 300, 'ease-in-out');

                // Manually set the fullscreen view element since it was just appended.
                this.setElement(parentGallery);
            },

            handleKeyPress: function(e){
                if (e.keyCode === 37) {
                    // left arrow
                    this.prevSlide();
                    return false;
                }
                if (e.keyCode === 39) {
                    // right arrow
                    this.nextSlide();
                    return false;
                }
                if (e.keyCode === 27) {
                    // escape
                    this.close();
                    return false;
                }
            }
        });
        return FullScreenCarousel;
});
/*   OnlineOpinion v5.6.2 Released: 7/26/2012. Compiled 07/26/2012 03:14:59 PM -0500 Branch: master f85964d08a7431113cc4cc29b4bea8abe31650d3 Components: Full The following code is Copyright 1998-2012 Opinionlab, Inc.  All rights reserved. Unauthorized use is prohibited. This product and other products of OpinionLab, Inc. are protected by U.S. Patent No. 6606581, 6421724, 6785717 B1 and other patents pending. http://www.opinionlab    */
define('libs/onlineopinion/oo_engine',[], function(){
    var OOo = {Browser:(function () {
        var a = navigator.userAgent, b = Object.prototype.toString.call(window.opera) === '[object Opera]', c = {IE:!!window.attachEvent && !b, Opera:b, WebKit:a.indexOf('AppleWebKit/') > -1, Chrome:a.indexOf('Chrome') > -1, Gecko:a.indexOf('Gecko') > -1 && a.indexOf('KHTML') === -1, MobileSafari:/Apple.*Mobile.*Safari/.test(a), PalmPre:a.indexOf('Pre/') > -1, BlackBerry:a.indexOf('BlackBerry') > -1, Fennec:a.indexOf('Fennec') > -1, IEMobile:a.indexOf('IEMobile') > -1, OperaMobile:a.search(/Opera (?:Mobi|Mini)/) > -1, ua:a}, d = false;
        c.isMobile = (c.MobileSafari || c.PalmPre || c.BlackBerry || c.Fennec || c.IEMobile || c.OperaMobile);
        return c;
    }())};
    OOo.Cache = {};
    OOo.instanceCount = 0;
    OOo.K = function () {
    };
    var OnlineOpinion = OnlineOpinion || OOo;
    (function () {
        function k(a) {
            return document.getElementById(a);
        }

        function j(a, b) {
            var c;
            for (c in b) {
                if (b.hasOwnProperty(c)) {
                    a[c] = b[c];
                }
            }
            return a;
        }

        function l(a, b, c, d) {
            if (a.addEventListener) {
                a.addEventListener(b, c, d);
            } else if (a.attachEvent) {
                a.attachEvent('on' + b, c);
            }
        }

        function q(a, b, c, d) {
            if (a.removeEventListener) {
                a.removeEventListener(b, c, d);
            } else if (a.detachEvent) {
                a.detachEvent('on' + b, c);
            }
        }

        function p(a) {
            var b = [], c;
            for (c in a) {
                if (a.hasOwnProperty(c)) {
                    b.push(c + '=' + (encodeURIComponent(a[c]) || ''));
                }
            }
            return b.join('&');
        }

        function s(a) {
            var b = p(a.metrics), c = a.tealeafId + '|' + a.clickTalePID + '/' + a.clickTaleUID + '/' + a.ClickTaleGetSID;
            b += '&custom_var=' + OOo.createLegacyVars(a.legacyVariables, c);
            if (a.metrics.type === 'OnPage') {
                b += '|iframe';
            }
            if (a.asm) {
                b += '&asm=2';
            }
            b += "&_" + 'rev=2';
            if (a.customVariables) {
                b += '&customVars=' + encodeURIComponent(OOo.serialize(a.customVariables));
            }
            return b;
        }

        function m(a, b) {
            var c = document, d = c.createElement('form'), e = c.createElement('input'), f = a.referrerRewrite;
            a.metrics.referer = location.href;
            if (f) {
                a.metrics.referer = OOo.referrerRewrite(f);
            }
            d.style.display = 'none';
            d.method = 'post';
            d.target = b || 'OnlineOpinion';
            d.action = a.onPageCard ? 'https://secure.opinionlab.com/ccc01/comment_card_json_4_0_b.asp?r=' + location.href : 'https://secure.opinionlab.com/ccc01/comment_card_d.asp';
            if (a.commentCardUrl) {
                d.action = a.commentCardUrl;
                if (a.onPageCard) {
                    d.action += '?r=' + location.href;
                }
            }
            e.name = 'params';
            e.value = s(a);
            d.appendChild(e);
            c.body.appendChild(d);
            return d;
        }

        function r() {
            return{width:screen.width, height:screen.height, referer:location.href, prev:document.referrer, time1:(new Date()).getTime(), time2:null, currentURL:location.href, ocodeVersion:'5.6.2'};
        }

        function t(a, b) {
            a = a || {};
            if (typeof a === 'string') {
                return b + '|' + a;
            }
            return a.override ? a.vars : b + (a.vars ? '|' + a.vars : '');
        }

        function n(a, b) {
            if (!b) {
                b = location;
            }
            if (typeof a === "string")return a;
            return a.searchPattern ? b.href.replace(a.searchPattern, a.replacePattern) : a.replacePattern;
        }

        var o = (function () {
            var a = document.body, b, c, d, e, f;
            if (document.createElement && a && a.appendChild && a.removeChild) {
                b = document.createElement('div');
                if (!b.getBoundingClientRect) {
                    return null;
                }
                b.innerHTML = 'x';
                b.style.cssText = 'position:fixed;top:100px;';
                a.appendChild(b);
                c = a.style.height;
                d = a.scrollTop;
                a.style.height = '3000px';
                a.scrollTop = 500;
                e = b.getBoundingClientRect().top;
                a.style.height = c;
                f = (e === 100);
                a.removeChild(b);
                a.scrollTop = d;
                return f;
            }
            return null;
        }()), v = (function () {
            if (navigator.appName === "Microsoft Internet Explorer" && navigator.userAgent.search("MSIE 6") !== -1) {
                return true;
            }
            var a = document.body, b, c;
            if (document.createElement && a && a.appendChild && a.removeChild) {
                b = document.createElement('iframe');
                c = false;
                b.setAttribute('name', 'oo_test');
                b.style.display = 'none';
                a.appendChild(b);
                c = !!!document.getElementsByName('oo_test')[0];
                a.removeChild(b);
                return c;
            } else {
                return null;
            }
        }());

        function w() {
            OOo.$('oo_container').style.display = 'none';
        }

        function u() {
            var a = OOo.$('oo_invitation_prompt');
            if (a) {
                var b = OOo.$('oo_container');
                this.showPrompt(b);
                return;
            }
            var c = window.XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject("Microsoft.XMLHTTP"), d = this, e = document.createElement('link'), f;
            c.onreadystatechange = function () {
                if (c.readyState !== 4) {
                    return;
                }
                d.showPrompt(c.responseText);
            };
            c.open("GET", this.options.pathToAssets + this.options.promptMarkup, true);
            c.send(null);
        }

        function y(a, b) {
            var c = document, d = typeof a === 'string' ? c.createElement('div') : a, e = c.createElement('div'), f, g, h = this.options, i;
            e.id = 'oo_invitation_overlay';
            d.id = 'oo_container';
            d.style.visibility = 'hidden';
            if (typeof a === 'string') {
                d.innerHTML = a;
                c.body.appendChild(d);
            }
            d.appendChild(e);
            i = OOo.$('oo_launch_prompt');
            if (h.companyLogo) {
                f = new Image();
                f.src = h.companyLogo;
                OOo.$('oo_company_logo').appendChild(f);
            }
            OOo.addEventListener(i, 'click', b.bind(this), false);
            if (h.clickCallbacks) {
                if (typeof h.clickCallbacks.yes === 'function') {
                    OOo.addEventListener(i, 'click', function () {
                        h.clickCallbacks.yes();
                    }, false);
                }
                if (typeof h.clickCallbacks.no === 'function') {
                    OOo.addEventListener(OOo.$('oo_no_thanks'), 'click', function () {
                        h.clickCallbacks.no();
                    }, false);
                }
            }
            if (h.neverShowAgainButton) {
                g = OOo.$('oo_never_show');
                g.style.visibility = 'visible';
                OOo.addEventListener(g, 'click', this.killPrompt.bind(this), false);
            }
            if (OOo.Browser.IE && !window.XMLHttpRequest) {
                e.style.position = 'absolute';
                e.style.width = Math.max(document.documentElement.clientWidth, document.body.offsetWidth) + 'px';
                e.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
                d.style.position = 'absolute';
            }
            d.style.visibility = 'visible';
            d.style.display = 'block';
            e.className = 'no_loading';
        }

        j(OOo, {extend:j, toQueryString:p, addEventListener:l, $:k, appendOOForm:m, removeEventListener:q, createMetrics:r, createLegacyVars:t, POSITION_FIXED_SUPPORTED:o, DYNAMIC_FRAME_NAME_IS_BUGGY:v, getFormParams:s, referrerRewrite:n, hidePrompt:w, getPrompt:u, showPrompt:y});
    }());
    (function () {
        function f(a) {
            if (!a) {
                return null;
            }
            switch (typeof a) {
                case'number':
                case'boolean':
                case'function':
                    return a;
                case'string':
                    return'\'' + a + '\'';
                case'object':
                    var b, c, d, e;
                    if (a.constructor === Array || typeof a.callee !== 'undefined') {
                        b = '[';
                        d = a.length;
                        for (c = 0; c < d - 1; c += 1) {
                            b += f(a[c]) + ',';
                        }
                        b += f(a[c]) + ']';
                    } else {
                        b = '{';
                        for (e in a) {
                            if (a.hasOwnProperty(e)) {
                                b += e + ':' + f(a[e]) + ',';
                            }
                        }
                        b = b.replace(/\,$/, '') + '}';
                    }
                    return b;
                default:
                    return null;
            }
        }

        OOo.extend(OOo, {serialize:f});
    }());
    (function () {
        function e(a, b, c) {
            var d;
            if (a.search(b[0]) !== -1) {
                OOo.createCookie(c, 0);
                return false;
            } else if (OOo.readCookie(c)) {
                d = parseInt(OOo.readCookie(c), 10);
                if ((a.search(b[d + 1]) !== -1) && (d + 1 !== b.length - 1)) {
                    OOo.createCookie(c, d + 1);
                    return false;
                } else if (a.search(b[d]) !== -1) {
                    return false;
                } else if (d + 1 === b.length - 1 && a.search(b.pop()) !== -1) {
                    OOo.eraseCookie(c);
                    return true;
                } else {
                    OOo.eraseCookie(c);
                    return false;
                }
            } else {
                return false;
            }
        }

        OOo.extend(OOo, {checkTunnel:e});
    }());
    (function () {
        function r(a) {
            var b = "", c;
            for (c = 7; c >= 0; c -= 1) {
                b += '0123456789abcdef'.charAt((a >> (c * 4)) & 0x0F);
            }
            return b;
        }

        function t(a) {
            var b = ((a.length + 8) >> 6) + 1, c = new Array(b * 16), d;
            for (d = 0; d < b * 16; d += 1) {
                c[d] = 0;
            }
            for (d = 0; d < a.length; d += 1) {
                c[d >> 2] |= a.charCodeAt(d) << (24 - (d % 4) * 8);
            }
            c[d >> 2] |= 0x80 << (24 - (d % 4) * 8);
            c[b * 16 - 1] = a.length * 8;
            return c;
        }

        function n(a, b) {
            var c = (a & 0xFFFF) + (b & 0xFFFF), d = (a >> 16) + (b >> 16) + (c >> 16);
            return(d << 16) | (c & 0xFFFF);
        }

        function o(a, b) {
            return(a << b) | (a >>> (32 - b));
        }

        function v(a, b, c, d) {
            if (a < 20) {
                return(b & c) | ((~b) & d);
            }
            if (a < 40) {
                return b ^ c ^ d;
            }
            if (a < 60) {
                return(b & c) | (b & d) | (c & d);
            }
            return b ^ c ^ d;
        }

        function w(a) {
            return(a < 20) ? 1518500249 : (a < 40) ? 1859775393 : (a < 60) ? -1894007588 : -899497514;
        }

        function u(a) {
            var b = t(a), c = new Array(80), d = 1732584193, e = -271733879, f = -1732584194, g = 271733878, h = -1009589776, i, k, j, l, q, p, s, m;
            for (s = 0; s < b.length; s += 16) {
                i = d;
                k = e;
                j = f;
                l = g;
                q = h;
                for (m = 0; m < 80; m += 1) {
                    if (m < 16) {
                        c[m] = b[s + m];
                    } else {
                        c[m] = o(c[m - 3] ^ c[m - 8] ^ c[m - 14] ^ c[m - 16], 1);
                    }
                    p = n(n(o(d, 5), v(m, e, f, g)), n(n(h, c[m]), w(m)));
                    h = g;
                    g = f;
                    f = o(e, 30);
                    e = d;
                    d = p;
                }
                d = n(d, i);
                e = n(e, k);
                f = n(f, j);
                g = n(g, l);
                h = n(h, q);
            }
            return r(d) + r(e) + r(f) + r(g) + r(h);
        }

        OOo.extend(OOo, {sha1:u});
    }());
    (function () {
        function h(a, b) {
            if (!b) {
                b = location;
            }
            var c = a.cookieName || 'oo_abandon', d = OOo.readCookie(c), e = a.startPage, f = a.endPage, g = a.middle;
            if (!d) {
                if (b.pathname.indexOf(e) !== -1) {
                    OOo.createCookie(c);
                }
                return false;
            } else if (b.pathname.indexOf(f) !== -1) {
                OOo.eraseCookie(c);
                return false;
            } else if (b.pathname.search(g) !== -1) {
                return false;
            } else {
                OOo.eraseCookie(c);
                return true;
            }
        }

        OOo.extend(OOo, {checkAbandonment:h});
    }());
    (function () {
        function d(a) {
            var b, c;
            for (b = a.length - 1; b >= 0; b -= 1) {
                if (a[b].read) {
                    c = OOo.readCookie(a[b].name);
                    if (!!c && c === a[b].value) {
                        return true;
                    } else if (typeof a[b].value === 'undefined' && !!OOo.readCookie(a[b].name)) {
                        return true;
                    }
                }
            }
            return false;
        }

        function e(a) {
            var b;
            for (b = a.length - 1; b >= 0; b -= 1) {
                if (a[b].set) {
                    OOo.createCookie(a[b].name, a[b].value, a[b].expiration);
                }
            }
        }

        OOo.extend(OOo, {checkThirdPartyCookies:d, setThirdPartyCookies:e});
    }());
    OOo.extend(Function.prototype, (function () {
        if (typeof Function.prototype.bind !== "undefined") {
            return;
        }
        var e = Array.prototype.slice;

        function f(a, b) {
            var c = a.length, d = b.length;
            while (d) {
                d -= 1;
                a[c + d] = b[d];
            }
            return a;
        }

        function g(a, b) {
            a = e.call(a, 0);
            return f(a, b);
        }

        function h(b) {
            if (arguments.length < 2 && typeof b === "undefined") {
                return this;
            }
            var c = this, d = e.call(arguments, 1);
            return function () {
                var a = g(d, arguments);
                return c.apply(b, a);
            };
        }

        return{bind:h};
    }()));
    (function () {
        function f(a) {
            if (!a) {
                a = location;
            }
            var b;
            if (a.host.search(/\.[a-z]+/) !== -1) {
                b = a.host.split('.').reverse();
                if (b.length > 3) {
                    return a.host;
                }
                b = '.' + b[1] + '.' + b[0];
            } else {
                b = a.host;
            }
            return b;
        }

        function g(a, b, c) {
            var d = '', e = '';
            if (c) {
                d = new Date();
                d.setTime(d.getTime() + (c * 1000));
                e = "; expires=" + d.toGMTString();
            }
            if (location.host !== f()) {
                document.cookie = a + "=" + b + e + "; path=/; domain=" + f() + ";";
            } else {
                document.cookie = a + "=" + b + e + "; path=/;";
            }
        }

        function h(a) {
            var b = a + "=", c = document.cookie.split(';'), d, e;
            for (e = 0; e < c.length; e += 1) {
                d = c[e];
                while (d.charAt(0) === ' ') {
                    d = d.substring(1, d.length);
                }
                if (d.indexOf(b) === 0) {
                    return d.substring(b.length, d.length);
                }
            }
            return null;
        }

        function i(a) {
            g(a, "", -1);
        }

        OOo.extend(OOo, {getCookieDomain:f, createCookie:g, readCookie:h, eraseCookie:i});
    }());
    OOo.Ocode = function (a) {
        var b = OOo.Browser, c, d;
        if (a.disableMobile && b.isMobile) {
            return;
        }
        if (a.disableNoniOS && (navigator.userAgent.search('Android') !== -1 || b.PalmPre || b.IEMobile || b.OperaMobile || b.Fennec)) {
            return;
        }
        OOo.instanceCount += 1;
        this.options = {tealeafCookieName:'TLTSID'};
        OOo.extend(this.options, a);
        c = this.options;
        c.metrics = OOo.createMetrics();
        this.frameName = c.onPageCard ? 'OnlineOpinion' + OOo.instanceCount : 'OnlineOpinion';
        if (c.cookie && OOo.Ocode.matchUrl(c.cookie, location)) {
            return;
        }
        if (c.thirdPartyCookies && OOo.checkThirdPartyCookies(c.thirdPartyCookies)) {
            return;
        }
        if (c.abandonment && !OOo.checkAbandonment(c.abandonment)) {
            return;
        }
        if (c.tunnel && !OOo.checkTunnel(location.pathname, c.tunnel.path, c.tunnel.cookieName)) {
            return;
        }
        if (c.events && c.events.onSingleClick) {
            this.singProbability = Math.random() < 1 - c.events.onSingleClick / 100;
        }
        c.tealeafId = OOo.readCookie(c.tealeafCookieName) || OOo.readCookie(c.sessionCookieName);
        if (c.events) {
            this.setupEvents();
            if (c.events.disableLinks || c.events.disableFormElements) {
                this.setupDisableElements();
            }
        }
        if (c.floating) {
            this.floating();
        } else if (c.bar) {
            this.bar();
        } else if (c.tab) {
            this.tab();
        }
    };
    OOo.Ocode.prototype = {show:function (a, b) {
        if (a === 'Tab' && b && b.preventDefault) {
            b.preventDefault();
        }
        if (this.onPageCardVisible) {
            return;
        }
        var c = this.options, d;
        if (c.events && c.events.prompt) {
            if (c.cookie)OOo.eraseCookie(c.cookie.name || 'oo_r');
            OOo.hidePrompt();
        }
        if (this.interruptShow) {
            return;
        }
        if (!this.floatingLogo && c.cookie && OOo.Ocode.matchUrl(c.cookie)) {
            return;
        }
        if (!c.floating && c.events && this.singProbability) {
            return;
        }
        if (c.events && c.events.onSingleClick) {
            this.singProbability = true;
        }
        if (c.cookie) {
            OOo.Ocode.tagUrl(c.cookie);
        }
        if (c.thirdPartyCookies) {
            if (OOo.checkThirdPartyCookies(c.thirdPartyCookies)) {
                return;
            }
            OOo.setThirdPartyCookies(c.thirdPartyCookies);
        }
        if (this.floatingLogo) {
            this.floatingLogo.children[0].blur();
        }
        if (this.floatingLogo && c.disappearOnClick) {
            this.floatingLogo.style.display = 'none';
        }
        if (a) {
            c.metrics.trigger = a;
        }
        if (c.clickTalePID && typeof window.ClickTale === 'function') {
            c.clickTaleUID = window.ClickTaleGetUID();
            c.clickTaleSID = window.ClickTaleGetSID();
        }
        if (c.onPageCard) {
            this.setupOnPageCC();
        } else {
            this.launchOOPopup();
        }
        d = c.floating || c.tab || c.bar;
        if (d && typeof d.onClickCallback === 'function') {
            d.onClickCallback();
        }
        if (OOo.Browser.IE) {
            return false;
        }
    }};
    OOo.extend(OOo.Ocode, {tagUrl:function (a, b) {
        if (!b) {
            b = location;
        }
        var c = a.name || 'oo_r', d = a.type === 'page' ? b.href : b.hostname, e = OOo.readCookie(c) || '';
        if (OOo.Ocode.matchUrl(a, b)) {
            return;
        }
        OOo.createCookie(c, e + OOo.sha1(d), a.expiration);
    }, matchUrl:function (a, b) {
        if (!b) {
            b = location;
        }
        var c = OOo.readCookie(a.name || 'oo_r'), d;
        if (!c) {
            return false;
        }
        d = a.type === 'page' ? b.href : b.hostname;
        return c.search(OOo.sha1(d)) !== -1;
    }});
    (function () {
        function g() {
            var a = this.options, b = a.newWindowSize || [545, 325], c = [parseInt((a.metrics.height - b[1]) / 2, 10), parseInt((a.metrics.width - b[0]) / 2, 10)], d, e, f = 'location=no,status=no,width=' + b[0] + ',height=' + b[1] + ',top=' + c[0] + ',left=' + c[1];
            var ie7 = OOo.Browser.IE && navigator.userAgent.search('MSIE 7') !== -1;
            a.metrics.time2 = (new Date()).getTime();
            a.metrics.type = 'Popup';
            if (a.asm) {
                f += ',scrollbars=1';
            }
            d = OOo.appendOOForm(a);
            e = window.open(ie7 ? a.commentCardUrl || 'https://secure.opinionlab.com/ccc01/comment_card_d.asp?' + d.children[0].value : '', 'OnlineOpinion', f);
            if (e && !ie7) {
                d.submit();
            }
        }

        OOo.extend(OOo.Ocode.prototype, {launchOOPopup:g});
    }());
    (function () {
        function k() {
            var a = this.options.events, b = [false, false], c = ['onExit', 'onEntry'], d = OOo.Browser.Opera ? 'unload' : 'beforeunload', e, f, g, h, i;
            if (a.prompt) {
                OOo.extend(this.options, {promptMarkup:a.prompt.promptMarkup || 'oo_event_prompt.html', neverShowAgainButton:false, pathToAssets:a.prompt.pathToAssets});
            }
            for (g = c.length - 1; g >= 0; g -= 1) {
                e = c[g];
                if (a[e]instanceof Array) {
                    h = a[e];
                    i = h.length;
                    while (i && !b[g]) {
                        i -= 1;
                        if (window.location.href.search(h[i].url) !== -1 && Math.random() >= 1 - h[i].p / 100) {
                            b[g] = true;
                        }
                    }
                } else if (a[e] && Math.random() >= 1 - a[e] / 100) {
                    b[g] = true;
                }
            }
            if (b[0]) {
                OOo.addEventListener(window, d, this.show.bind(this, 'onExit'), false);
            }
            if (b[1]) {
                if (a.delayEntry) {
                    window.setTimeout(function () {
                        if (a.prompt)this.getPrompt(); else this.show();
                    }.bind(this, 'onEntry'), a.delayEntry * 1000);
                } else {
                    if (a.prompt)this.getPrompt(); else this.show('onEntry');
                }
            }
        }

        function j(a) {
            var b = a || window.event, c = a.target || a.srcElement, d = this.options.events, e = c.parentNode, f = 5, g = 0;
            while (e && (c.nodeName !== 'A' || c.nodeName !== 'INPUT') && g !== f) {
                if (e.nodeName === 'A') {
                    c = e;
                }
                e = e.parentNode;
                g += 1;
            }
            if (d.disableFormElements && c.tagName === "INPUT" && (c.type === 'submit' || c.type === 'image')) {
                this.interruptShow = true;
            }
            if (d.disableLinks && c.nodeName === 'A' && c.href.substr(0, 4) === 'http' && c.href.search(d.disableLinks) !== -1) {
                this.interruptShow = true;
            }
        }

        function l(a) {
            this.interruptShow = true;
        }

        function q() {
            OOo.addEventListener(document.body, 'mousedown', j.bind(this));
            if (!this.options.events.disableFormElements) {
                return;
            }
            var a = document.getElementsByTagName('form'), b;
            for (b = a.length - 1; b >= 0; b -= 1) {
                OOo.addEventListener(a[b], 'submit', l.bind(this));
            }
        }

        OOo.extend(OOo.Ocode.prototype, {setupEvents:k, setupDisableElements:q, getPrompt:function () {
            OOo.getPrompt.call(this);
        }, showPrompt:function (a) {
            if (this.options.cookie) {
                OOo.Ocode.tagUrl(this.options.cookie);
            }
            OOo.showPrompt.call(this, a, this.show);
        }});
    }());
    OOo.extend(OOo.Ocode.prototype, {floating:function () {
        var d = document, e = this.floatingLogo = document.createElement('div'), f = d.createElement('div'), g = d.createElement('div'), h = d.createElement('div'), i = d.createElement('span'), k = this.options.floating, j = OOo.$(k.contentId), l = '10px', q = k.id, p = d.createElement('span'), s, m, r, t, n, o, v, w;

        function u(a) {
            return a.offsetLeft + a.offsetWidth;
        }

        function y(a) {
            t.style.left = u(j) + 'px';
        }

        p.innerHTML = "Screen reader users: Please switch to forms mode for this link.";
        p.className = "screenReader";
        if (q) {
            e.id = q;
        }
        e.className = 'oo_feedback_float';
        g.className = 'oo_transparent';
        f.className = 'olUp';
        h.className = 'olOver';
        f.tabIndex = 0;
        f.onkeyup = function (a) {
            s = a || window.event;
            if (s.keyCode !== 13) {
                return;
            }
            this.show();
        }.bind(this);
        f.innerHTML = k.caption || 'Feedback';
        e.appendChild(p);
        e.appendChild(f);
        i.innerHTML = k.hoverCaption || 'Click here to<br>rate this page';
        h.appendChild(i);
        e.appendChild(h);
        e.appendChild(g);
        function z(a) {
            var b = d.documentElement.scrollTop || d.body.scrollTop, c = d.documentElement.clientHeight || document.body.clientHeight;
            e.style.top = (b + c - (v || 0) - 10) + 'px';
        }

        if (OOo.Browser.MobileSafari) {
            if (OOo.Browser.ua.search('OS 4') !== -1) {
                m = window.innerHeight;
                e.style.bottom = null;
                e.style.top = (window.pageYOffset + window.innerHeight - 60) + 'px';
                w = function (a) {
                    r = window.pageYOffset - (m - window.innerHeight);
                    e.style.webkitTransform = 'translateY(' + r + 'px)';
                };
                OOo.addEventListener(window, 'scroll', w, false);
                setTimeout(w, 100);
            }
        } else if (!OOo.POSITION_FIXED_SUPPORTED) {
            e.style.position = 'absolute';
            e.style.bottom = '';
            OOo.addEventListener(window, 'scroll', z, false);
            OOo.addEventListener(window, 'resize', z, false);
            if (d.compatMode === "BackCompat") {
                e.style.background = "white";
            }
        }
        if (k.position && k.position.search(/Content/) && j) {
            t = this.spacer = d.createElement('div');
            n = OOo.Browser.WebKit ? d.body : d.documentElement;
            t.id = 'oo_feedback_fl_spacer';
            t.style.left = u(j) + 'px';
            d.body.appendChild(t);
            switch (k.position) {
                case'rightOfContent':
                    o = function (a) {
                        e.style.left = (u(j) - n.scrollLeft) + 'px';
                        if (!OOo.POSITION_FIXED_SUPPORTED) {
                            o = null;
                        }
                    };
                    break;
                case'fixedPreserveContent':
                    o = function (a) {
                        var b = OOo.Browser.IE ? d.body.clientWidth : window.innerWidth, c = OOo.POSITION_FIXED_SUPPORTED ? n.scrollLeft : 0;
                        if (b <= u(j) + e.offsetWidth + parseInt(l, 10)) {
                            e.style.left = (u(j) - c) + 'px';
                        } else {
                            e.style.left = '';
                            e.style.right = l;
                        }
                    };
                    break;
                case'fixedContentMax':
                    o = function (a) {
                        var b = OOo.Browser.IE ? d.body.clientWidth : window.innerWidth;
                        if (b <= u(j) + e.offsetWidth + parseInt(l, 10)) {
                            e.style.left = '';
                            e.style.right = l;
                            if (!OOo.POSITION_FIXED_SUPPORTED && a && a.type === 'scroll') {
                                e.style.left = (d.body.clientWidth + d.body.scrollLeft - 105) + 'px';
                            }
                        } else {
                            e.style.left = (u(j) - n.scrollLeft) + 'px';
                            e.style.right = '';
                        }
                    };
                    break;
            }
            window.setTimeout(o, 0);
            OOo.addEventListener(window, 'scroll', o, false);
            OOo.addEventListener(window, 'resize', o, false);
            OOo.addEventListener(window, 'resize', y, false);
        } else {
            e.style.right = l;
        }
        OOo.addEventListener(e, 'click', this.show.bind(this, 'Floating'), false);
        OOo.addEventListener(e, 'touchstart', this.show.bind(this, 'Floating'), false);
        d.body.appendChild(e);
        if (!OOo.POSITION_FIXED_SUPPORTED && !OOo.Browser.MobileSafari) {
            g.style.height = e.clientHeight + 'px';
            v = e.clientHeight;
            setTimeout(z, 100);
        }
    }, removeFloatingLogo:function () {
        document.body.removeChild(this.floatingLogo);
        if (this.spacer) {
            document.body.removeChild(this.spacer);
        }
    }});
    OOo.extend(OOo.Ocode.prototype, {bar:function () {
        var d = document, e = this.floatingLogo = d.createElement('div'), f = d.createElement('span'), g, h, i, k = d.documentElement.scrollTop || d.body.scrollTop;

        function j(a) {
            var curtop = 0;
            var b = 0;
            if (a.offsetParent) {
                do {
                    b += a.offsetLeft;
                    curtop += a.offsetTop;
                } while (a = a.offsetParent);
                return[b, curtop];
            }
        }

        function l(a) {
            var b = document.activeElement, c;
            if (!b)return;
            c = j(b);
            if (!c)return;
            if (c[1] + b.clientHeight > (window.innerHeight || document.body.clientHeight) + (window.pageYOffset || document.body.scrollTop) - e.clientHeight)window.scrollBy(0, b.clientHeight + 20);
        }

        this.reflowBar = OOo.K;
        e.id = 'oo_bar';
        f.innerHTML = this.options.bar.caption || 'Feedback';
        e.appendChild(f);
        e.tabIndex = 0;
        e.onkeyup = function (a) {
            var b = a || window.event;
            if (b.keyCode !== 13) {
                return;
            }
            this.show();
        }.bind(this);
        OOo.addEventListener(e, 'click', this.show.bind(this, 'Bar'));
        document.body.className += document.body.className < 1 ? 'oo_bar' : ' oo_bar';
        document.body.appendChild(e);
        if (OOo.Browser.IE) {
            if (d.compatMode === 'CSS1Compat') {
                g = function (a) {
                    if (a && a.type === 'resize') {
                        setTimeout(g, 50);
                    }
                    e.style.top = (d.documentElement.scrollTop + document.documentElement.clientHeight - e.clientHeight - 1) + 'px';
                    e.style.width = (Math.max(d.documentElement.clientWidth, d.body.offsetWidth)) + 'px';
                };
            } else {
                g = function (a) {
                    e.style.top = (d.body.scrollTop + document.body.clientHeight - e.clientHeight - 1) + 'px';
                    e.style.width = (Math.max(d.documentElement.clientWidth, d.body.offsetWidth) - 22) + 'px';
                };
            }
            e.style.position = 'absolute';
            OOo.addEventListener(window, 'scroll', g, false);
            OOo.addEventListener(window, 'resize', g, false);
            this.reflowBar = function () {
                e.style.display = 'none';
                g();
                e.style.display = 'block';
            };
            g();
        } else if (OOo.Browser.MobileSafari && OOo.Browser.ua.search('OS 4') !== -1) {
            h = window.innerHeight;
            e.style.bottom = null;
            e.style.top = (window.pageYOffset + window.innerHeight - 22) + 'px';
            g = function (a) {
                i = window.pageYOffset - (h - window.innerHeight);
                e.style.webkitTransform = 'translateY(' + i + 'px)';
            };
            OOo.addEventListener(window, 'scroll', g, false);
            setTimeout(g, 100);
        }
        OOo.addEventListener(document.body, 'keyup', l, false);
    }});
    OOo.extend(OOo.Ocode.prototype, {tab:function () {
        var e = document, f = this.floatingLogo = e.createElement('div'), g = e.createElement('div'), h = e.createElement('span'), i = this.options.tab;

        function k(a) {
            var b = e.documentElement.scrollTop || e.body.scrollTop, c = e.documentElement.scrollLeft || e.body.scrollLeft, d = e.documentElement.clientHeight || document.body.clientHeight;
            f.style.top = (b + (d / 2 - f.clientHeight / 2)) + 'px';
            if ((!i.position || i.position === 'right'))f.style.right = (-1 * c + 2) + 'px';
        }

        function j(a) {
            f.style.top = window.pageYOffset + (window.innerHeight / 2 - f.clientHeight / 2) + 'px';
            f.style.right = document.documentElement.clientWidth - window.innerWidth - window.pageXOffset - 15 + 'px';
        }

        f.id = 'oo_tab';
        f.className = 'oo_tab_' + (i.position || 'right');
        if (!OOo.POSITION_FIXED_SUPPORTED && !OOo.Browser.MobileSafari) {
            f.style.position = 'absolute';
            if ((!i.position || i.position === 'right') && OOo.Browser.IE) {
                f.className += ' oo_tab_ie_right';
                if (OOo.Browser.ua.search('IE 6') === -1) {
                    OOo.addEventListener(window, 'scroll', k, false);
                    OOo.addEventListener(window, 'resize', k, false);
                }
            }
        }
        f.tabIndex = 0;
        f.onkeyup = function (a) {
            var b = a || window.event;
            if (b.keyCode !== 13) {
                return;
            }
            this.show();
        }.bind(this);
        g.appendChild(h);
        f.appendChild(g);
        OOo.addEventListener(f, 'click', this.show.bind(this, 'Tab'), false);
        e.body.appendChild(f);
        if (OOo.Browser.MobileSafari && OOo.Browser.ua.search('OS 4') !== -1) {
            f.style.position = 'absolute';
            OOo.addEventListener(window, 'scroll', j, false);
            setTimeout(j, 100);
        }
    }});
    OOo.extend(OOo.Ocode.prototype, {setupOnPageCC:function () {
        var e = document, f = OOo.Cache.overlay || e.createElement('div'), g = this.wrapper = e.createElement('div'), h = e.createElement('div'), i = e.createElement('div'), k = e.createElement('span'), j = this.frameName, l = e.createElement(OOo.DYNAMIC_FRAME_NAME_IS_BUGGY ? '<iframe name="' + j + '">' : 'iframe'), q = e.createDocumentFragment(), p = this.options, s = p.onPageCard, m = 'https://secure.opinionlab.com/ccc01/comment_card_json_4_0_b.asp', r, t, n, o = false, v = this, w, u, y, z, A, C, B;

        function x(a) {
            if (a && a.preventDefault) {
                a.preventDefault();
            }
            document.body.focus();
            l.tabIndex = -1;
            l.title = "empty";
            l['aria-hidden'] = 'true';
            f.style.display = 'none';
            f.className = '';
            e.body.removeChild(g);
            if (window.postMessage) {
                OOo.removeEventListener(window, 'message', A);
            } else {
                window.clearInterval(t);
            }
            o = false;
            v.onPageCardVisible = false;
            return false;
        }

        A = OOo.Ocode.postMessageHandler(function (a) {
            var b = parseInt(a, 10), c, d;
            if (b > 0) {
                if (o) {
                    return;
                }
                o = true;
                c = window.innerHeight || e.documentElement.clientHeight || e.body.clientHeight;
                d = b;
                B = g.offsetTop;
                if (d + B > c) {
                    d = c - 40 - B;
                    l.style.width = '555px';
                }
                l.style.height = d + 'px';
                g.style.visibility = 'visible';
                if (k.clientHeight < 20) {
                    k.style.height = g.offsetHeight + 'px';
                }
                f.className = "no_loading";
                v.onPageCardVisible = true;
            } else if (a === 'submitted') {
                x();
            }
            if (OOo.Browser.IE && e.compatMode === "BackCompat") {
                window.scrollTo(0, 0);
            }
        }, v.options.commentCardUrl);
        p.metrics.type = 'OnPage';
        OOo.Cache.overlay = f;
        f.id = 'oo_overlay';
        f.style.display = 'block';
        f.className = '';
        i.className = 'iwrapper';
        g.className = 'oo_cc_wrapper';
        h.className = 'oo_cc_close';
        h.innerHTML = 'X';
        h.title = 'Click to close comment card';
        g.style.visibility = 'hidden';
        h.tabIndex = 0;
        h.onkeyup = function (a) {
            var b = a || window.event;
            if (b.keyCode !== 13) {
                return;
            }
            x();
        };
        if (OOo.Browser.IE) {
            l.frameBorder = '0';
            if (!window.XMLHttpRequest || e.compatMode === "BackCompat") {
                C = Math.max(e.documentElement.clientWidth, e.body.offsetWidth);
                f.style.position = 'absolute';
                f.style.width = e.compatMode === "BackCompat" ? (C - 21) + 'px' : C + 'px';
                f.style.height = Math.max(e.documentElement.clientHeight, e.body.offsetHeight) + 'px';
                g.style.position = 'absolute';
                OOo.addEventListener(window, 'scroll', function () {
                    f.style.top = (e.body.scrollTop + document.body.clientHeight - f.clientHeight) + 'px';
                    g.style.top = (e.body.scrollTop + B + 25) + 'px';
                });
            }
        }
        OOo.addEventListener(h, 'click', x);
        if (s.closeWithOverlay && !OOo.Browser.isMobile) {
            g.appendChild(k);
            k.onclick = x;
            f.onclick = x;
        }
        l.src = ' ';
        l.name = j;
        i.appendChild(h);
        i.appendChild(l);
        g.appendChild(i);
        q.appendChild(g);
        q.appendChild(f);
        e.body.appendChild(q);
        if (window.postMessage) {
            OOo.addEventListener(window, "message", A);
        } else {
            t = setInterval(A, 500);
        }
        p.metrics.time2 = (new Date()).getTime();
        r = OOo.appendOOForm(p, j);
        r.submit();
    }});
    OOo.extend(OOo.Ocode, {postMessageHandler:function (d, e, f) {
        return function (a) {
            var b = 'https://secure.opinionlab.com', c;
            if (!f) {
                f = location;
            }
            if ((a && !(a.origin === b || a.origin.indexOf(e) !== 0)) || (!a && f.hash.search('OL=') === -1)) {
                return false;
            }
            c = a ? a.data : f.hash.split('=').pop();
            if (!a && location.hash) {
                location.hash = '';
            }
            d(c);
            return c;
        };
    }});
    OOo.Invitation = function (a) {
        if (OOo.Browser.isMobile) {
            return;
        }
        this.options = {tunnelCookie:'oo_inv_tunnel', repromptTime:604800, responseRate:50, repromptCookie:'oo_inv_reprompt', promptMarkup:'oo_inv_prompt.html', promptStyles:'oo_inverstitial_style.css', percentageCookie:'oo_inv_percent', pagesHitCookie:'oo_inv_hit', popupType:'popunder', promptDelay:0, neverShowAgainButton:false, loadPopupInBackground:false, tealeafCookieName:'TLTSID', monitorWindow:'oo_inv_monitor.html', beforePrompt:OOo.K};
        this.popupShown = false;
        OOo.extend(this.options, a);
        var b = this.options, c = parseInt(OOo.readCookie(b.pagesHitCookie), 10) || 0;
        OOo.Invitation.friendlyDomains = b.friendlyDomains || null;
        if (location.search.search('evs') !== -1) {
            b.loadPopupInBackground = true;
            this.launchPopup();
            OOo.createCookie(b.repromptCookie, 1, b.repromptTime === -1 ? 0 : b.repromptTime);
        }
        setTimeout(function () {
            if (!window.oo_inv_monitor) {
                return;
            }
            if (b.area && location.href.search(b.area) === -1) {
                this.options.popupType = 'popup';
                this.launchPopup();
            } else if (b.goal && location.href.search(b.goal) !== -1) {
                window.oo_inv_monitor.close();
            }
        }.bind(this), 1600);
        if (OOo.readCookie(b.repromptCookie)) {
            return;
        }
        if (b.thirdPartyCookies && OOo.checkThirdPartyCookies(b.thirdPartyCookies)) {
            return;
        }
        if (!OOo.readCookie(b.percentageCookie)) {
            OOo.createCookie(b.percentageCookie, (Math.random() > 1 - (b.responseRate / 100)) ? "1" : "0");
        }
        if (typeof b.promptTrigger !== 'undefined') {
            if (b.promptTrigger instanceof RegExp) {
                if (!window.location.href.match(b.promptTrigger)) {
                    return;
                }
            } else if (b.promptTrigger instanceof Array) {
                if (!OOo.checkTunnel(location.pathname, b.promptTrigger, b.tunnelCookie)) {
                    return;
                }
            }
        }
        c += 1;
        OOo.createCookie(b.pagesHitCookie, c);
        if (b.pagesHit && c < b.pagesHit) {
            return;
        }
        OOo.eraseCookie(b.tunnelCookie);
        if (OOo.readCookie(b.percentageCookie) === '1') {
            window.setTimeout(function () {
                OOo.createCookie(b.repromptCookie, 1, b.repromptTime);
                this.options.beforePrompt();
                this.getPrompt();
            }.bind(this), b.promptDelay * 1000);
        }
    };
    OOo.Invitation.prototype = {getPrompt:function () {
        OOo.getPrompt.call(this);
    }, showPrompt:function (a) {
        OOo.showPrompt.call(this, a, this.launchPopup);
    }, launchPopup:function () {
        if (this.popupShown) {
            return;
        }
        this.popupShown = true;
        var b = this.options, c = window.location.href, d = b.popupType === 'popup' ? 'https://secure.opinionlab.com/ccc01/comment_card.asp?' : b.pathToAssets + b.monitorWindow + '?' + (new Date()).getTime() + '&', e, f = [], g = b.asm ? [555, 500] : [400, 335], h, i = OOo.createMetrics(), k = OOo.readCookie(b.tealeafCookieName), j;
        if (b.clickTalePID && window.ClickTaleGetUID && window.ClickTaleGetSID) {
            k += '|' + [b.clickTalePID, window.ClickTaleGetUID(), window.ClickTaleGetSID()].join('/');
        }
        g = b.newWindowSize || g;
        j = 'location=no,status=no,width=' + g[0] + ',height=' + g[1];
        if (b.referrerRewrite) {
            i.referer = OOo.referrerRewrite(b.referrerRewrite);
        }
        if (b.thirdPartyCookies) {
            OOo.setThirdPartyCookies(b.thirdPartyCookies);
        }
        e = OOo.toQueryString(i) + '&type=Invitation';
        if (b.customVariables) {
            e += '&customVars=' + encodeURIComponent(OOo.serialize(b.customVariables));
        }
        e += '&custom_var=' + OOo.createLegacyVars(b.legacyVariables, k);
        if (b.asm) {
            e += '&asm=2';
            j += ',scrollbars=1';
        }
        h = window.open(d + e, 'OnlineOpinionInvitation', j);
        if (!b.loadPopupInBackground && OOo.$('oo_container')) {
            OOo.hidePrompt();
        }
        if (b.popupType === 'popunder') {
            if (!OOo.Browser.Chrome) {
                h.blur();
                window.focus();
            } else {
                if (!b.loadPopupInBackground) {
                    window.alert(b.chromeMainWinPrompt || 'Please fill out the form behind this window when you are finished.');
                }
                if (b.chromeSurveyPrompt) {
                    setTimeout(function (a) {
                        h.postMessage(b.chromeSurveyPrompt, "*");
                    }, 500);
                }
            }
        } else if (window.oo_inv_monitor) {
            window.blur();
            h.focus();
        }
    }, killPrompt:function () {
        if (this.options.clickCallbacks && typeof this.options.clickCallbacks.no === 'function') {
            this.options.clickCallbacks.no();
        }
        OOo.createCookie(this.options.repromptCookie, 1, 157680000);
        OOo.hidePrompt();
    }};
    OOo.extend(OOo.Invitation, {navigateToFriendlyDomain:function (a) {
        location.href = a;
    }});
    return OOo;
});

/**
 * @fileoverview App view.
 * @author Chris Manning
 */
define('appview',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'state',
    'text!siteconfig.json',
    'resizestop',
    'views/pages/404',
    'views/modules/header',
    'views/modules/carousel/carousel-fullscreen',
    'libs/onlineopinion/oo_engine'
],
function(
    $,
    _,
    Backbone,
    App,
    PubSub,
    StateManager,
    siteConfig,
    ResizeStop,
    ErrorView,
    Header,
    FullScreenCarousel,
    OOo
)
{

    /**
     * View class.
     * Global event listener. Not intended to render an actual view.
     */
    var AppView = Backbone.View.extend({

        // View element.
        el: 'body',

        // Event listeners.
        events: {
            'click': 'triggerRoute',
            'submit form.ui-ajax-form': 'triggerForm'
        },

        /**
         * Initialize view.
         * @param {Object} options View options passed in during init.
         */
        initialize: function(options) {

            // Event Proxy.
            window.appViewEventProxy = PubSub;
            window.App = App;

            // Set global properties/lookups.
            this.DEBUG = App.get('DEBUG');
            this.$win = App.get('win');

            this.pubSub = {
                'opinionlab:show': this.openOpinionLabFeedback,
                'openFullScreenCarousel': this.openFullScreenCarousel
            };
            PubSub.attach(this.pubSub, this);
        },

        start: function() {
            // Initialize global header.
            if (!window.chromeless) {
                window.header = this.header = new Header();
            }
            if (window.location.search && window.location.search.indexOf('404=true') > -1){
                this.loadAjaxError('/404.html');
            }
            // Responsive images plugin.
            this.$win.on('resizestop.' + this.cid, function(event) {
                // Fire resize event.
                PubSub.trigger('resize:app');
            }).trigger('resizestop');

            StateManager.start($.parseJSON(siteConfig));
        },

        /**
            Returns an instance of the header
        */
        getHeader: function(){
            return this.header;
        },

        openFullScreenCarousel: function(options){
            return new FullScreenCarousel(options);
        },

        /**
         * Load Error
         */
        loadAjaxError: function(path) {
            StateManager.fetchHtml(path).done(function(htmlFrag) {
                var view = new ErrorView({ajax: true, htmlFrag: htmlFrag});
            });
        },

        openOpinionLabFeedback: function(){
            (new OOo.Ocode({})).show();
        },

        destroy: function(){
            this.undelegateEvents();
            delete window.header;
            delete window.appViewEventProxy;
            delete window.App;
            this.$win.off('.' + this.cid);
            PubSub.unattach(this.pubSub, this);
        },

        /**
         * Handle global links.
         * @param {Event} e Link click event.
         */
        triggerRoute: function(e){
            var href, $targetLink = $(e.target).closest('a');
            App.setTrack($targetLink);
            StateManager.updateActivityTimestamp();
            if (!$targetLink.length || e.isDefaultPrevented() ||
                e.metaKey || e.altKey || e.which == 2 || $targetLink.attr('target')) {
                // Skip preventing default, let the browser do it's thing.
                return;
            }
            href = $.trim($targetLink.attr('href'));
            if (!Modernizr.history) {
                if (App.getDefinedRoute(href) && window.chromeless) {
                    // reattach ?chromeless=true to internal urls
                    href = $.trim($targetLink.attr('href'));
                    href += ((href.indexOf('?') === -1) ? '?' : '&') + 'chromeless=true';
                    $targetLink.attr('href', href);
                }
            } else {
                if (!App.isValidUrl(href)) {
                    e.preventDefault();
                } else {
                    href = App.getDefinedRoute(href);
                    if (href !== null) {
                        if (window.chromeless) {
                            // reattach ?chromeless=true to internal urls
                            href += ((href.indexOf('?') === -1) ? '?' : '&') + 'chromeless=true';
                        }
                        Backbone.history.navigate(href, {trigger: true});
                        e.preventDefault();
                    }
                }
            }
        },

        /**
         * Handle global search form submits.
         * @param {Event} e Link click event.
         */
        triggerForm: function(e){
            var form = $(e.currentTarget),
                mappingData = form.data('mapping'),
                templateObj = {},
                url = form.attr('action');
            if (e.isDefaultPrevented()) {
                return;
            }
            if (mappingData) {
                $.each(form.serializeArray(), function(index, value){
                    templateObj[value.name] = value.value;
                });
                url += _.template(mappingData, templateObj);
            }
            if (!App.isValidUrl(url)) {
                e.preventDefault();
            } else {
                url = App.getDefinedRoute(url);
                if (url !== null) {
                    if (window.chromeless) {
                        // reattach ?chromeless=true to internal urls
                        url += ((url.indexOf('?') === -1) ? '?' : '&') + 'chromeless=true';
                    }
                    Backbone.history.navigate(url, {trigger: true});
                    e.preventDefault();
                }
            }

        }

    });

    /**
     * Return view class.
     */
    return new AppView();
});

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
  var o   = parseUri.options,
    m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;

  while (i--) uri[o.key[i]] = m[i] || "";

  uri[o.q.name] = {};
  uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
    if ($1) uri[o.q.name][$1] = $2;
  });

  return uri;
}

parseUri.options = {
  strictMode: false,
  key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
  q:   {
    name:   "queryKey",
    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  },
  parser: {
    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
    loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  }
};
// Raven.js
//
// Originally based on the Arecibo JavaScript client.
//
// Requires:
//     * Either jQuery (>1.5) or Zepto.js (>0.8).
//     * parseUri (included in the full and minified distribution files)

(function(){
    // Save a reference to the global object (`window` in the browser, `global`
    // on the server).
    

    var root = this;

    var Raven;
    root.Raven = Raven = {};

    var self = Raven;

    Raven.VERSION = '0.7.1';

    // jQuery, Zepto, or Ender owns the `$` variable.
    var $ = root.jQuery || root.Zepto || root.ender;
    if (typeof($) === 'undefined') {
        throw "Raven requires one of the following libraries: jQuery, Zepto, or ender";
    }
    if (root.jQuery === $ && $.fn.jquery < '1.5.0') {
        throw "A newer version of jQuery is required";
    }

    Raven.options = {
        secretKey: undefined,  // The global key if not using project auth
        publicKey: undefined,  // Leave as undefined if not using project auth
        servers: [],
        projectId: 1,
        logger: 'javascript',
        site: undefined,
        dataCallback: null,
        signatureUrl: undefined,
        fetchHeaders: false,  // Generates a synchronous request to your server
        testMode: false,  // Disables some things that randomize the signature
        ignoreErrors: [],
        ignoreUrls: []
    };

    Raven.funcNameRE = /function\s*([\w\-$]+)?\s*\(/i;

    Raven.config = function(config) {
        var servers = [];

        if (typeof(config) === "string") {
            if (config.indexOf('http') === 0) {
                // new-style DSN configuration
                config = Raven.parseDSN(config);
            } else {
                throw "Base64 encoded config is no longer supported - use DSN";
            }
        }

        $.each(config, function(key, option) {
            self.options[key] = option;
        });

        // Expand server base URLs into API URLs
        $.each(self.options.servers, function(i, server) {
            // Add a trailing slash if one isn't provided
            if (server.slice(-1) !== '/') {
                server += '/';
            }
            servers.push(server + 'api/' + self.options.projectId + '/store/');
        });
        self.options.servers = servers;

    };

    Raven.parseDSN = function(dsn) {
        var uri = parseUri(dsn);
        var path_idx = uri.path.lastIndexOf('/');
        var project_id;
        var path;

        if (path_idx === -1) {
            project_id = uri.path.substr(1);
            path = '';
        } else {
            path = uri.path.substr(1, path_idx);
            project_id = uri.path.substr(path_idx + 1);
        }

        return {
            servers: [uri.protocol + '://' + uri.host + ':' + uri.port + '/' + path],
            publicKey: uri.user,
            secretKey: uri.password,
            projectId: project_id
        };
    };

    Raven.getHeaders = function() {
        var headers = {};

        if (self.options.fetchHeaders && !self.options.testMode) {
            headers = $.ajax({
                type: 'HEAD',
                url: root.location,
                async: false
            }).getAllResponseHeaders();
        }

        headers.Referer = document.referrer;
        headers["User-Agent"] = navigator.userAgent;
        return headers;
    };

    Raven.parseHeaders = function(headers_string) {
        /*
         * Parse the header string returned from getAllResponseHeaders
         */
        var headers = {};
        $.each(headers_string.split('\n'), function(i, header) {
            var name = header.slice(0, header.indexOf(':')),
                value = header.slice(header.indexOf(':') + 2);
            headers[name] = value;
        });
        return headers;
    };

    Raven.getSignature = function(message, timestamp, callback) {
        if (self.options.signatureUrl) {
            $.ajax({
                type: 'POST',
                url: self.options.signatureUrl,
                data: {
                    message: message,
                    timestamp: timestamp
                },
                dataType: 'json',
                success: function(data) {
                    callback(data.signature);
                }
            });
        } else {
            callback();
        }
    };

    Raven.getAuthHeader = function(signature, timestamp) {
        var header = "Sentry sentry_version=2.0, ";
        header += "sentry_timestamp=" + timestamp + ", ";
        header += "sentry_client=raven-js/" + self.VERSION;
        if (self.options.publicKey) {
            header += ", sentry_key=" + self.options.publicKey;
        }
        if (signature) {
            header += ", sentry_signature=" + signature;
        }
        return header;
    };

    Raven.captureException = function(e, options) {
        var label, lineno, fileurl, traceback;

        if (e.line) {  // WebKit
            lineno = e.line;
        } else if (e.lineNumber) {  // Mozilla
            lineno = e.lineNumber;
        }

        if (e.sourceURL) {  // Webkit
            fileurl = e.sourceURL;
        } else if (e.fileName) {  // Mozilla
            fileurl = e.fileName;
        }

        if (e["arguments"] && e.stack) {
            traceback = self.chromeTraceback(e);
        } else if (e.stack) {
            // Detect edge cases where Chrome doesn't have 'arguments'
            if (e.stack.indexOf('@') == -1) {
                traceback = self.chromeTraceback(e);
            } else {
                traceback = self.firefoxOrSafariTraceback(e);
            }
        } else {
            traceback = [{"filename": fileurl, "lineno": lineno}];
            traceback = traceback.concat(self.otherTraceback(Raven.captureException));
        }

        self.process(e, fileurl, lineno, traceback, options);
    };

    Raven.captureMessage = function(msg, options) {
        var data = self.arrayMerge({
            'message': msg
        }, options);
        
        self.send(data);
    };

    Raven.process = function(message, fileurl, lineno, traceback, options) {
        var type, stacktrace, label, data;

        if (typeof(message) === 'object') {
            type = message.name;
            message = message.message;
        }

        if ($.inArray(message, self.options.ignoreErrors) >= 0) {
            return;
        }


        if (traceback) {
            stacktrace = {"frames": traceback};
            fileurl = fileurl || traceback[0].filename;
        } else if (fileurl) {
            stacktrace = {
                "frames": [{
                    "filename": fileurl,
                    "lineno": lineno
                }]
            };
        }

        for (var i = 0; i < self.options.ignoreUrls.length; i++) {
            if (self.options.ignoreUrls[i].test(fileurl)) {
                return;
            }
        }

        label = lineno ? message + " at " + lineno : message;

        data = self.arrayMerge({
            "sentry.interfaces.Exception": {
                "type": type,
                "value": message
            },
            "sentry.interfaces.Stacktrace": stacktrace,
            "culprit": fileurl,
            "message": label
        }, options);

        self.send(data);
    };

    Raven.arrayMerge = function(arr1, arr2) {
        if (typeof(arr2) === "undefined") {
            return arr1;
        }
        $.each(arr2, function(key, value){
            arr1[key] = value;
        });
        return arr1;
    };

    Raven.trimString = function(str) {
        return str.replace(/^\s+|\s+$/g, "");
    };

    Raven.chromeTraceback = function(e) {
        /*
         * First line is simply the repeated message:
         *   ReferenceError: aldfjalksdjf is not defined
         *
         * Following lines contain error context:
         *   at http://localhost:9000/1/group/306:41:5
         */
        var chunks, fn, filename, lineno, fileBits,
            traceback = [],
            lines = e.stack.split('\n');
        $.each(lines.slice(1), function(i, line) {
            // Trim the 'at ' from the beginning, and split by spaces
            chunks = Raven.trimString(line).slice(3);
            if (chunks == "unknown source") {
                return;  // Skip this one
            } else {
                chunks = chunks.split(' ');
            }

            if (chunks.length > 2) {
                // If there are more than 2 chunks, there are spaces in the
                // filename
                fn = chunks[0];
                filename = chunks.slice(1).join(' ');
                lineno = '(unknown)';
            } else if (chunks.length == 2) {
                // If there are two chunks, the first one is the function name
                fn = chunks[0];
                filename = chunks[1];
            } else {
                fn = '(unknown)';
                filename = chunks[0];
            }

            if (filename && filename !== '(unknown source)') {
                if (filename[0] === '(') {
                    // Remove parentheses
                    filename = filename.slice(1, -1);
                }
                // filename should be: <scheme>://<uri>:<line>:<column>
                // where :<column> is optional
                fileBits = filename.split(':');
                lineno = fileBits[2];
                filename = fileBits.slice(0, 2).join(':');
            }

            traceback.push({
                'function': fn,
                'filename': filename,
                'lineno': lineno
            });
        });
        return traceback;
    };

    Raven.firefoxOrSafariTraceback = function(e) {
        /*
         * Each line is a function with args and a filename, separated by an ampersand.
         *   unsubstantiatedClaim("I am Batman")@http://raven-js.com/test/exception.js:7
         *
         * Anonymous functions are presented without a name, but including args.
         *   (66)@http://raven-js.com/test/vendor/qunit.js:418
         *
         */
        var chunks, fn, args, filename, lineno,
            traceback = [],
            lines = e.stack.split('\n');
        $.each(lines, function(i, line) {
            if (line) {
                chunks = line.split('@');
                if (chunks[0]) {
                    fn = chunks[0].split('(');

                    if (fn.length > 1 && fn[1] != ')') {
                        args = fn[1].slice(0, -1).split(',');
                    } else {
                        args = undefined;
                    }

                    if (fn[0]) {
                        fn = fn[0];
                    } else {
                        fn = '(unknown)';
                    }
                } else {
                    fn = '(unknown)';
                }

                if (chunks.length > 1) {
                    filename = chunks[1].split(':');
                    lineno = filename.slice(-1)[0];
                    filename = filename.slice(0, -1).join(':');
                } else if (chunks[0] == '[native code]') {
                    fn = '(unknown)';
                    filename = '[native code]';
                    lineno = 0;
                    args = undefined;
                }

                traceback.push({
                    'function': fn,
                    'filename': filename,
                    'lineno': lineno,
                    'vars': {'arguments': args}
                });
            }
        });
        return traceback;
    };

    Raven.otherTraceback = function(callee) {
        /*
         * Generates best-efforts tracebacks for other browsers, such as Safari
         * or IE.
         */
        var fn, args,
            ANON = '<anonymous>',
            traceback = [],
            max = 9;
        while (callee && traceback.length < max) {
            fn = callee.name || (self.funcNameRE.test(callee.toString()) ? RegExp.$1 || ANON : ANON);
            if (callee["arguments"]) {
                args = self.stringifyArguments(callee["arguments"]);
            } else {
                args = undefined;
            }
            traceback.push({
                'filename': '(unknown source)',
                'lineno': '(unknown)',
                'function': fn,
                'post_context': callee.toString().split('\n'),
                'vars': {'arguments': args}
            });
            callee = callee.caller;
        }
        return traceback;
    };

    Raven.stringifyArguments = function(args) {
        /*
         * Converts a callee's arguments to strings
         */
        var fn,
            self = this,
            UNKNOWN = '<unknown>',
            results = [];

        $.each(args, function(i, arg) {
            if (arg === undefined) {
                results.push('undefined');
            } else if (arg === null) {
                results.push('null');
            } else if (arg instanceof Array) {
                results.push(self.stringifyArguments(arg));
            } else if (arg.constructor) {
                fn = arg.constructor.name || (self.funcNameRE.test(arg.constructor.toString()) ? RegExp.$1 || UNKNOWN : UNKNOWN);
                if (fn == 'String') {
                    results.push('"' + arg + '"');
                } else if (fn == 'Number' || fn == 'Date') {
                    results.push(arg);
                } else if (fn == 'Boolean') {
                    results.push(arg ? 'true' : 'false');
                } else {
                    results.push(fn);
                }
            } else {
                results.push(UNKNOWN);
            }
        });

        return results;
    };

    Raven.pad = function(n, amount) {
        var i,
            len = ('' + n).length;
        if (typeof(amount) === "undefined") {
            amount = 2;
        }
        if (len >= amount) {
            return n;
        }
        for (i=0; i < (amount - len); i++) {
            n = '0' + n;
        }
        return n;
    };

    Raven.dateToISOString = function(date) {
        if (Date.prototype.toISOString) {
            return date.toISOString();
        }
        
        return date.getUTCFullYear() + '-' +
            self.pad(date.getUTCMonth() + 1) + '-' +
            self.pad(date.getUTCDate()) + 'T' +
            self.pad(date.getUTCHours()) + ':' +
            self.pad(date.getUTCMinutes()) + ':' +
            self.pad(date.getUTCSeconds()) + '.' +
            self.pad(date.getUTCMilliseconds(), 3) + 'Z';
    };

    Raven.send = function(data) {
        var encoded_msg,
            timestamp= new Date().getTime(),
            url = root.location.protocol + '//' + root.location.host + root.location.pathname,
            querystring = root.location.search.slice(1);  // Remove the ?

        data = self.arrayMerge({
            "project": self.options.projectId,
            "logger": self.options.logger,
            "site": self.options.site,
            "timestamp": new Date(),
            "sentry.interfaces.Http": {
                "url": url,
                "querystring": querystring,
                "headers": self.getHeaders()
            }
        }, data);

        if (typeof(self.options.dataCallback) == 'function') {
            data = self.options.dataCallback(data);
        }

        data.timestamp = self.dateToISOString(data.timestamp);

        encoded_msg = JSON.stringify(data);
        self.getSignature(encoded_msg, timestamp, function(signature) {
            var header = self.getAuthHeader(signature, timestamp);
            $.each(self.options.servers, function (i, server) {
                $.ajax({
                    type: 'POST',
                    url: server,
                    data: encoded_msg,
                    dataType: 'json',
                    headers: {
                        // We send both headers, since Authentication may be blocked,
                        // and custom headers arent supported in IE9
                        'X-Sentry-Auth': header,
                        'Authentication': header
                    }
                });
            });
        });
    };
}).call(this);

define("raven", function(){});

define('settealium',['pubsub','fwinfo','underscore','backbone'], function(PubSub,FwInfo,_) {
    var _curPage= {}, _queue= [],
        _utag= function(method, data) {
            _queue.push([method, data])
        };
    function utagtrack(typ, dat) {
        for (var p in dat){
            if (dat.hasOwnProperty(p) && dat[p]){
                dat[p]= (''+dat[p]).toLowerCase()
            }
        }
        utag.track(typ, dat);
    }
    var _setTealiumClass= Backbone.Model.extend({
        initialize: function() {
            this.clickName="";
            this.clickPage="";
            PubSub.on('page:load', function(e) {_setTealium.page_load(e)});
            PubSub.on('uotrack', function(e) {_setTealium.uotrack(e)});
            PubSub.on('heattrack', function(e) {_setTealium.heattrack(e)});
            PubSub.on('slide:change', function(e) {_setTealium.slide_change(e)});
            PubSub.on('video:load', function(e) {_setTealium.video_load(e)});
            PubSub.on('vitrack', function(e) {_setTealium.vitrack(e)});
            if (self.utag){
                this.ready();
            }
        },
        ready: function() {
            _.defer(function() {
                for (var j= 0; j < _queue.length; j++){
                    utagtrack.apply(utag, _queue[j]);
                }
                _queue= [];
                _utag = function(method, data) {
                    utagtrack(method, data)
                    s_ut.prop41= ''; /* prevent uotrack from contaminating exit link tracking */
                };
            });
        },
        relevant_data: function(pageinfo, eventtype) {
            if (!pageinfo.aws) pageinfo.aws= 'undefined';
            if (!pageinfo.ssts) pageinfo.ssts= 'bugpages'; 
            var cstlist= pageinfo.aws.replace(/\/\/*$/,'').split('/'),
                halfHour= new Date(1800000 * parseInt(new Date().getTime()/1800000, 10)),
                h= halfHour.getHours(),
                hashvalue=location.hash.match(/\bht=([^&]*)/) && RegExp.$1, 
                cspvalue = window.location.search.match(/[?&]csp=([^&]*)/i) && RegExp.$1
                sstslist= pageinfo.ssts.split('/');
            this.clickName=(function(hash, sess) {return hash||sess})(hashvalue, FwInfo.getandclearsessionvalue('clickName'));
            this.clickPage= FwInfo.getandclearsessionvalue('clickPage');
            return {
                assetid: pageinfo.assetid,
                atyponuserid: FwInfo.getsessionvalue("atyponid"),
                blogname: pageinfo.blogname||pageinfo.blognamebackup||'', /* using two values to work around an inconsistency in core -- right solution would be for core to always put the name of the blog in front_attrs sitename instead of sometimes using front_attrs topic_name (like on-politics) */
                byline: pageinfo.byline||'',
                category: cstlist[0],
                clickName: this.clickName,
                clickPage: this.clickPage,
                contenttype: pageinfo.contenttype,
                cst: cstlist.slice(0,3).join(':'),
                dayofweek: 'sunday monday tuesday wednesday thursday friday saturday'.split(' ')[new Date().getDay()],
                eventtype: eventtype,
                gcionid: document.cookie.match(/\bGCIONID=([^;]*)/) && RegExp.$1,
                halfhour: (1+(h+11)%12)+':'+(function(h) {return h.substr(h.length-2)})('0'+halfHour.getMinutes())+(h>11 ?' pm' :' am'),
                linkTrackVars: 'prop1',
                pathName:pageinfo.pathName||'',
                prevpath: FwInfo.getandclearsessionvalue('prevpath'),
                referrerhost:(hashvalue)?document.referrer.split('/')[2]:"",
                refreshed: FwInfo.getandclearsessionvalue('refreshed'),
                searchkeywords: pageinfo.searchkeywords,
                section: sstslist[0],
                ssts: sstslist.join(':'),
                subcategory: cstlist.slice(0,2).join(':'),
                subsection: sstslist.slice(0,2).join(':'),
                templatetype: pageinfo.templatetype,
                topic: sstslist.slice(0,3).join(':'),
                typeofday: ((new Date().getDay()+8)%7>1) ?'weekday' :'weekend',
                uniqueuserid: FwInfo.getsessionvalue("uniqueid"),
                videoincluded:pageinfo.videoincluded||"no",
                taxonomykeywords:pageinfo.taxonomykeywords||'',
                gallerytitle:pageinfo.gallerytitle||'',
                galleryindex:pageinfo.galleryindex||'',
                queryparamtrack:cspvalue||'',
                viralVideoDomain : "",
                videoContentProvider : "",
                videoFulllengthUrl : "",
                videoName: "",
                videoPlayerName : "",
                keywords: "",
                videoDuration: "",
                milestonetrack : "",
                noinitialanalytics:pageinfo.noinitialanalytics||''
            };
        },
        page_load: function(detail) {
            var data= _curPage= _setTealium.relevant_data(detail, 'page:load');
            FwInfo.setsessionvalue('prevpath', document.location.pathname);
            _utag('view', data);
            _.defer(function(){self.s_ut && s_ut.getPPVSetup && s_ut.getPPVSetup()});
        },
        uotrack: function(detail) {
            if ('string' != typeof detail) {
                console.error('uotrack has been given a non-string event argument', detail);
                detail= (detail||{}).prop41 || 'somethingbad';
            } 
            var vars= detail.match(/{% *[a-z0-9_]* *%}/gi);
            if (vars) {
                for (var j=0; j<vars.length; j++){
                    var v= vars[j];
                    var name= v.match(/{% *([a-z0-9_]*) *%}/) && RegExp.$1;
                    detail= detail.replace(v, _curPage[name]);
                }
            }
            var data= {clickName: detail, eventtype: 'uotrack', linkTrackEvents: 'None', linkTrackVars: 'prop41'};
            _utag('link', data);
        },
        vitrack: function(detail) {
            if ('string' != typeof detail) {
                console.error('vitrack has been given a non-string event argument', detail);
                detail= (detail||{}).prop9 || 'somethingbad';
            } 
             
            var data= {milestonetrack: detail, eventtype: 'vitrack', linkTrackEvents: 'None', linkTrackVars: 'prop9'};
            _utag('link', data);
        },
        heattrack: function(clickName) {
            FwInfo.setsessionvalue('clickName', clickName);
            FwInfo.setsessionvalue('clickPage', location.href);
        },
        slide_change: function(detail) {
            var data= _curPage, cstlist, sstslist;
            try {
                cstlist= detail.cst.split('/');
                sstslist= detail.ssts.split('/');
            } catch (er) {
                console.error('Invalid page', er.stack || er.stacktrace || er.message);
                return;
            }
            data.byline = "";
            data.clickName= FwInfo.getandclearsessionvalue('clickName');
            data.contenttype= detail.contenttype;
            data.videoincluded = detail.videoincluded ||"no";
            data.gallerytitle= detail.gallery_title;
            data.galleryindex= detail.gallery_index;
            data.assetid= detail.gallery_id;
            data.eventtype= 'slide:change';
            data.templatetype= '';
            data.category= cstlist[0];
            data.cst= cstlist.slice(0,3).join(':');
            data.refreshed="";
            data.section= sstslist[0];
            data.ssts= sstslist.join(':');
            data.subcategory= cstlist.slice(0,2).join(':');
            data.subsection= sstslist.slice(0,2).join(':');
            data.topic= sstslist.slice(0,3).join(':');
            data.pathName= detail.pathName||'';
            data.viralVideoDomain = "";
            data.videoContentProvider = "";
            data.videoFulllengthUrl = "";
            data.videoName = "";
            data.videoDuration = "";
            data.videoPlayerName = "";
            data.keywords =  "";
            data.milestonetrack = "";
            _utag('view', data);
        },
        video_load : function(detail) {
            var data= _curPage;
            
            data.byline = "";
            data.clickName= this.clickName;
            data.clickPage= this.clickPage;
            data.category= detail.category;
            data.cst= detail.cst;
            data.assetid= detail.assetid;
            data.refreshed="";
            data.section= detail.section;
            data.ssts= detail.ssts;
            data.subcategory= detail.subcategory;
            data.subsection= detail.subsection;
            data.topic= detail.topic;
            data.videoPlayerName = detail.videoPlayerName;
            data.completion = detail.completion;
            data.keywords = detail.keywords;
            data.contenttype = detail.contenttype;
            data.videoName = detail.videoName;
            data.videoDuration = detail.videoDuration;
            data.eventtype = detail.eventtype;
            data.pathName= detail.pathName||'';
            data.videoContentID = detail.contentid;
            data.viralVideoDomain = detail.viralVideoDomain;
            data.videoContentProvider = detail.videoContentProvider;
            data.templatetype = detail.templateType;
            data.noinitialanalytics = false;
            data.videoincluded = "yes";
            data.videoFulllengthUrl = detail.videoFulllengthUrl;
            _utag('view', data);
        }
    });
    var _setTealium= new _setTealiumClass();
    return _setTealium;
});

/**
 * @fileoverview Bootstrap file for USAToday.com.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 * @author kris.hedstrom@f-i.com (Kris Hedstrom)
 */

// Avoid console errors (IE doesn't create a console object if the debugger isn't open).
if(typeof window.console === 'undefined' || typeof window.console.log === 'undefined') {
    window.console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

window.onerror= function() {
    function process_error() {
        if (window.js_debug_chance > Math.random())
            Raven.process.apply(Raven, arguments);
    }
    if (self.Raven && window.js_debug_chance) {
        Raven.config({
            publicKey: 'aedac890efdb434d95e273b667b470ce',
            servers: ['http://app.getsentry.com'],
            projectId: '3635',
            dataCallback: function (data) {
                data.multiplier= 1/window.js_debug_chance;
                // FIXME: identify the git commit and build instance
                // for example, from:     git log -1 | awk '/commit/{print $2}'
                return data;
            }
        });
        window.onerror= process_error;
        process_error.apply(Raven, arguments);
    }
};

/**
 * Base 'App' initialization.
 */
require.config({
    paths: {
        jquery: 'libs/jquery/jquery-1.8.3',
        jqueryui: 'libs/jquery/plugins/jquery-ui-1.9.2.custom.min',
        underscore: 'libs/underscore/underscore',
        backbone: 'libs/backbone/backbone-dev',
        raven: 'libs/getsentry/raven-0.7.1',
        pubsub: 'libs/backbone/plugins/pubsub',
        app: 'models/app',
        appview: 'views/app',
        state: 'managers/statemanager',
        baseview: 'views/baseview',
        baseappview: 'views/baseappview',
        simpleoverlay: 'views/simple-overlay',
        cookie: 'libs/jquery/plugins/jquery.cookie',
        easing: 'libs/jquery/plugins/jquery.easing.1.3',
        animatecolors: 'libs/jquery/plugins/jquery.animate-colors-min',
        resizestop: 'libs/jquery/plugins/jquery.resizeStop',
        chosen: 'libs/jquery/plugins/chosen.jquery.min',
        mousewheel: 'libs/jquery/plugins/jquery.mousewheel.min',
        transform: 'libs/jquery/plugins/audio-player/jquery.transform',
        uiPageTurn: 'libs/jquery.ui-page-turn',
        uiFlip: 'libs/jquery.ui-flip',
        transformSupport: 'libs/jquery.transformSupport',
        fwinfo: 'fw/models/fwinfo',
        settealium: 'fw/models/settealium',
        facebook: 'fw/facebook/facebook',
        userauth: 'fw/models/userauth',
        googleplus: 'fw/googleplus/googleplus',
        fitvids: 'libs/jquery/plugins/jquery.fitvids',
        datepicker: 'libs/jquery/plugins/jquery-ui.datepicker.min',
        draggable: 'libs/jquery/plugins/jquery-ui.draggable.min',
        touchpunch: 'libs/jquery/plugins/jquery-ui.touch-punch.min',
        touchswipe: 'libs/jquery/plugins/jquery.touchSwipe',
        admanager: 'managers/admanager',
        sharedAdPosition: 'views/modules/partner/shared-ad-position',
        meteredAdPosition: 'views/modules/partner/metered-ad-position',
        indexedAdPosition: 'views/modules/partner/indexed-ad-position',
        directAdPosition: 'views/modules/partner/direct-ad-position',
        adLogger: 'views/modules/partner/ad-logger',
        text: 'libs/require/text',
        form: 'views/modules/form/base-form'
    },

    /**
     * The use of the order plugin has been discontinued. Define necessary dependencies
     * using shim.
     *
     * https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0
     */
    shim: {
        'raven': ['jquery'],
        'cookie': ['jquery'],
        'easing': ['jquery'],
        'animatecolors': ['jquery'],
        'resizestop': ['jquery'],
        'chosen': ['jquery'],
        'mousewheel': ['jquery'],
        'circleplayer': ['jquery'],
        'grab': ['jquery'],
        'jplayer': ['jquery'],
        'touchpunch': ['jquery', 'jqueryui'],
        'touchswipe': ['jquery'],
        'transform': ['jquery'],
        'fitvids': ['jquery'],
        'uiPageTurn': ['jquery', 'transformSupport'],
        'libs/flot/jquery.flot' :  ['libs/flot/excanvas']
    }
});

/**
 * Base 'App' initializaiton.
 */
require([
    'appview',  
    'userauth',
    'raven',
    'settealium',
    'fwinfo'
],
function(AppView) {

    /**
     * App View.
     */
    AppView.start();
});

define("main", function(){});

/**
 * @fileoverview Builds a shared ad position on the page
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('sharedAdPosition',[
    'jquery',
    'underscore',
    'views/modules/partner/ad-position',
    'app',
    'admanager'
],
function($, _, AdPosition, App, AdManager) {
    

    var SharedAdPosition = AdPosition.extend({
        /**
         * Initializes the view
         * @param options
         */
        initialize: function(options) {
            options = $.extend({
                // required options
                adType: null, // name of this ad type in DFP (ie, pushdown, heroflip), can be an array
                // this specifies whether this is where the 'slot' lives in case an IAB ad appears in the slot
                defaultPosition: false
            }, options);

            // call base class initialize
            AdPosition.prototype.initialize.call(this, options);

            AdManager.registerSharedAdPosition(this);
        },

        isDefaultPosition: function() {
            return this.options.defaultPosition;
        },

        getAdType: function() {
            return this.options.adType;
        },

        refreshPosition: function() {
            AdManager.refreshSharedAdPosition(this.getAdPlacement());
        },

        destroy: function(removeEl) {
            AdPosition.prototype.destroy.call(this, removeEl);
            AdManager.destroySharedAdPosition(this);
        }
    });
    return SharedAdPosition;
});
/**
 * @fileoverview Handles Leave Behind enabled Ads
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 */

 define('views/modules/partner/leavebehind',[
    'jquery', 
    'underscore', 
    'baseview',
    'adLogger'
],
function(
    $, 
    _, 
    BaseView,
    AdLogger
) {

        /**
         * View class.
         */
        var LeaveBehindAd = BaseView.extend({

            events: {
                click: 'onClick'
            },
            /**
             * Initialize view.
             */
            initialize: function(options) {
                options = $.extend({
                    template: '<div class="leavebehind-sponsoredby">' +
                            'sponsored by' +
                        '</div>' +
                        '<img class="leavebehind-image" src="<%= imageUrl %>" alt="<%= altText %>"/>',
                    onShowAd: null,
                    imageUrl: '',
                    altText: '',
                    isCompact: true,
                    isStagFront: false,
                    adObj: null
                }, options);

                if (this.options.isStagFront) {
                    this.stagMasthead = this.$el.siblings('.stag-masthead-name');
                    this.stagMasthead.css('text-align', 'left');
                }

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);

                if (!this.$el.prop('id')) {
                    this.$el.prop('id', _.uniqueId('ad-position-'));
                }

                // Tell me about it
                AdLogger.logDebug('LeaveBehind initialized', this);
            },

            /**
             * Clean up the view (no argument).
             */
            destroy: function(removeEl) {
                this.hide();
                if (this.stagMasthead) {
                    this.stagMasthead.css('text-align', '');
                    this.stagMasthead = null;
                }
                BaseView.prototype.destroy.call(this, false);
            },

            render: function(adObj){
                var adState = adObj.getCreativeState({
                    isOpen: true
                });
                if (this.options.isCompact){
                    this.$el.addClass('compact');
                }else{
                    this.$el.removeClass('compact');
                }
                this.$el.empty().append(_.template(this.options.template, this.options));

                if (adState.isOpen) {
                    adState.isOpen = false;
                    adObj.setCreativeState(adState);
                    if (this.options.onShowAd) {
                        this.options.onShowAd();
                    }
                } else {
                    // show the leave behind
                    this.show();
                    // set up tracking of the leave behind instead of the actual ad
                    adObj.trackAd(this.$el);
                }
            },

            onClick: function(){
                this.hide();
                if (this.options.onShowAd){
                    this.options.onShowAd();
                }
                return false;
            }
        });

        /**
         * Return view class.
         */
        return LeaveBehindAd;
    }
);

/**
 * @fileoverview Handles pushdown for ad executions
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 * @author Chad Shryock <cdshryock@gannett.com>
 */

define('views/modules/partner/pushdown-ad',[
    'jquery',
    'underscore',
    'app',
    'baseview',
    'sharedAdPosition',
    'views/modules/partner/leavebehind',
    'adLogger',
    'animatecolors'
],
function(
    $,
    _,
    App,
    BaseView,
    SharedAdPosition,
    LeaveBehind,
    AdLogger
) {
    
    var PushdownView = BaseView.extend({

        events: {
            'click .partner-pushdown-ad > .partner-close': 'closeAdClick'
        },

        initialize: function(options) {
            options = $.extend({
                adClasses: '',
                animations: {
                    vertical: {
                        duration: 350,
                        easing: 'cubic-bezier(0.645, 0.045, 0.355, 1.000)'
                    }
                }
            }, options);

            _.bindAll(this, 'onAdReady', 'showAd', 'beforeAdRender');

            // call base class initialize
            BaseView.prototype.initialize.call(this, options);

            this.useCSSTransforms = false;
            this.$body = App.get('body');
            this.$pushdown = this.$('.partner-pushdown-ad');
            this.$bigHeadline = this.$('.big-headline');
            AdLogger.logDebug('Pushdown Advertisment initialized', this);
        },

        render: function(currentCardInfo, isCardBumped){
            this.subviews.adPosition = new SharedAdPosition({
                el: this.$pushdown,
                adSizes: ['pushdown', 'iabpushdown', 'iabpushdown2', 'billboard'],
                adPlacement: 'high_impact',
                adType: ['pushdown', 'risingstar'],
                onAdReady: this.onAdReady,
                beforeAdRender: this.beforeAdRender
            });
            this.currentCardInfo = currentCardInfo;
            this.isCardBumped = isCardBumped;
        },

        beforeAdRender: function(adInfo){
            this.adType = adInfo.adType;
            this.onCardWidthChange(this.currentCardInfo);
        },

        destroy: function(removeEl) {
            // no need to cleanup ad, it gets cleaned up by the ad position
            if (this.showingAd) {
                this.closeAd(true);
            } else {
                this.clearBackground();
            }
            BaseView.prototype.destroy.call(this, removeEl);
        },

        onAdReady: function(adInfo) {
            this.backgroundSolidColor = adInfo.backgroundSolidColor;
            this.backgroundRepeatingImage = adInfo.backgroundRepeatingImage;
            if (adInfo.adType === 'Pushdown+') {
                this.persistBackground = true;
                this.changeBackground();
                this.$pushdown.css({display: 'block', height: 0});
            }
            if (adInfo.leaveBehindImage && adInfo.leaveBehindText) {
                this.subviews.adLeaveBehind = new LeaveBehind({
                    el: this.$('.partner-leavebehind'),
                    onShowAd: this.showAd,
                    imageUrl: adInfo.leaveBehindImage,
                    altText: adInfo.leaveBehindText,
                    isCompact: this.isCardBumped
                });
                this.subviews.adLeaveBehind.render(this.subviews.adPosition);
            } else {
                this.showAd();
            }
        },

        showAd: function() {
            var pushdownHeight;
            this.showingAd = true;
            this.subviews.adPosition.showAd(this.currentCardInfo.cardWidth, 615);
            if (this.$pushdown.hasClass('iab-risingstar')) {
                if (this.isCardBumped) {
                    this.$pushdown.css('margin', '0 auto 25px');
                }
            } else {
                // rising star ads have their own logic for revealing the ads
                this.$pushdown.css({height: 0});
                pushdownHeight = 615 - this.getBigHeadlineHeight();
                this.$bigHeadline.css('visibility', 'hidden');
                $.when( this.animate(this.$pushdown, 'height', pushdownHeight, this.options.animations.vertical.duration),
                        this.animate(this.$pushdown, 'top', 0, this.options.animations.vertical.duration))
                    .done(_.bind(function(){
                    if (this.subviews.adPosition) {
                        this.subviews.adPosition.playAd();
                    }
                }, this));
            }
            this.changeBackground();
        },

        closeAdClick: function(e){
            e.preventDefault();
            this.closeAd();
        },

        getBigHeadlineHeight: function(){
            return this.$bigHeadline.height() || 0;
        },

        closeAd: function(clearBackground) {
            var bigHeadlineHeight = this.getBigHeadlineHeight();
            this.showingAd = false;
            this.subviews.adPosition.stopAd();
            $.when( this.animate(this.$pushdown, 'height', 0, this.options.animations.vertical.duration),
                    this.animate(this.$pushdown, 'top', bigHeadlineHeight, this.options.animations.vertical.duration))
                .done(_.bind(function() {
                this.$bigHeadline.css('visibility', 'visible');
                if (this.subviews.adLeaveBehind) {
                    this.subviews.adLeaveBehind.show();
                }
            }, this));
            if (!this.persistBackground || clearBackground) {
                this.clearBackground();
            }
            return false;
        },

        changeBackground: function() {
            if (!this.backgroundSolidColor || this.backgroundSolidColor === 'transparent') {
                return;
            }

            // Body Background goes to the png
            this.$body.addClass('partner-background');

            // Animate into the background color
            this.animate(this.$body, 'background-color', this.backgroundSolidColor, 200, 'ease-in').done(_.bind(function() {
                if (this.backgroundRepeatingImage) {
                    this.changeBackgroundImage(this.backgroundRepeatingImage);
                } else {
                    this.changeBackgroundImage('/static/images/pixels/pixel-transparent.png');
                }
            }, this));
        },

        changeBackgroundImage: function(imageSrc) {
            this.$body.css({
                'background-image': 'url(\'' + imageSrc + '\')',
                'background-repeat': 'repeat'
            });
        },

        clearBackground: function() {
            this.$body.css({
                'background-image': '',
                'background-repeat': ''
            });
            this.animate(this.$body, 'background-color', 'rgb(246,246,246)', 200, 'ease-in').done(_.bind(function() {
                this.$body.removeClass('partner-background');
            }, this));
        },

        onCardWidthChange: function(newCardInfo) {
            var bigHeadlineHeight = this.getBigHeadlineHeight();
            this.currentCardInfo = newCardInfo;
            if (this.adType === 'Pushdown+') {
                this.$pushdown.css('top', bigHeadlineHeight);
            }
            this.$pushdown.removeClass(this.options.adClasses).addClass(newCardInfo.adClass);
            this.subviews.adPosition.resizeAd(newCardInfo.cardWidth, 615);
        }

    });
    return PushdownView;

});

/**
 * @fileoverview Handles metered ad overlays
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 * @author Chad Shryock <cdshryock@gannett.com>
 */

define('views/modules/partner/overlay-ad-base',[
    'jquery',
    'underscore',
    'pubsub',
    'state',
    'baseview'
],
function(
    $,
    _,
    PubSub,
    StateManager,
    BaseView
) {
    
    var OverlayView = BaseView.extend({

        events: {
            'click .partner-close,.film': 'onClickCloseButton'
        },

        /**
         * Initialize view.
         */
        initialize: function(options) {
            this.listen();

            // call base class initialize
            BaseView.prototype.initialize.call(this, options);

            this.$placement = this.$('.partner-placement');
        },

        showAd: function() {
            StateManager.setActiveAppFixed();
            this.showingAd = true;
            this.show(true).done(_.bind(function() {
                if (this.subviews.ad) {
                    this.subviews.ad.playAd();
                }
            }, this));
        },

        stopAd: function() {
            if (this.subviews.ad) {
                this.subviews.ad.stopAd();
            }
        },

        onAdReady: function() {
            if (this.subviews.ad) {
                this.showAd();
            }
        },

        /**
         * Clean up the view (no argument).
         */
        destroy: function(removeEl) {
            this.close();
            BaseView.prototype.destroy.call(this, removeEl);
        },

        findSizeForAd: function() {
            // default to small
            var obj = {
                adSizeClass: 'size-s',
                adTop: '50%',
                adHeight: 450,
                adWidth: 600
            };
            // get visible area height and width
            var breakingNewsHeight = StateManager.getBreakingNewsOffset();
            // 80 is for the padding between the header/bottom of browser and the ad
            var viewportHeight = document.documentElement.clientHeight - breakingNewsHeight - 80;
            // 160 = 80 for the arrows. 40 for padding between the arrows and the ad
            var viewportWidth = document.documentElement.clientWidth - 160;
            // check size
            if (viewportWidth > 1080 && viewportHeight > 810) {
                obj.adSizeClass = 'size-xl';
                obj.adHeight = 810;
                obj.adWidth = 1080;
            } else if (viewportWidth > 936 && viewportHeight > 700) {
                obj.adSizeClass = 'size-l';
                obj.adHeight = 700;
                obj.adWidth = 936;
            } else if (viewportWidth > 768 && viewportHeight > 576) {
                obj.adSizeClass = 'size-m';
                obj.adHeight = 576;
                obj.adWidth = 768;
            }

            obj.adTop = (((document.documentElement.clientHeight - breakingNewsHeight - obj.adHeight) / 2) + breakingNewsHeight) + 'px';
            return obj;
        },

        listen: function() {
            this.pubSub = {};

            // Tell pubSub object
            this.pubSub['resize:app'] = this.onResize;
            this.pubSub['breakingbar:after:open'] = this.onResize;
            this.pubSub['breakingbar:after:close'] = this.onResize;
        },

        onClickCloseButton: function(e) {
            e.preventDefault();
            this.close(true);
        },

        close: function(animate) {
            if (this.showingAd && this.subviews.ad) {
                this.showingAd = false;
                StateManager.clearActiveAppFixed();
                this.subviews.ad.stopAd();
                this.hide(animate);
            }
        },

        onReady: function() {
            if (this.config.startVisible) {
                this.showOverlay();
                PubSub.trigger('partner:' + this.config.dfp.ecid + ':creative:defaultshow');
            } else {
                PubSub.trigger('partner:' + this.config.dfp.ecid + ':leavebehind:defaultshow');
            }
        },

        onResize: function() {
            var obj = this.findSizeForAd();
            this.$placement.removeClass('size-s size-m size-l size-xl').addClass(obj.adSizeClass).css({'top': obj.adTop});
            if (this.subviews.ad) {
                this.subviews.ad.resizeAd(obj.adWidth, obj.adHeight);
            }
        }
    });
    return OverlayView;
});

/**
 * @fileoverview Handles shared slot ad overlays
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 */

define('views/modules/partner/overlay-ad-fronts',[
    'jquery',
    'underscore',
    'views/modules/partner/overlay-ad-base',
    'sharedAdPosition',
    'views/modules/partner/leavebehind',
    'adLogger'
],
function(
    $,
    _,
    OverlayAdBase,
    SharedAdPosition,
    LeaveBehind,
    AdLogger
) {
    
    var OverlaySharedAd = OverlayAdBase.extend({

        /**
         * Initialize view.
         */
        initialize: function(options) {
            options = $.extend({
                adSizes: ['elastic'],
                adType: 'elastic',
                adPlacement: 'high_impact',
                isCardBumped: true,
                isStagFront: false
            }, options);

            _.bindAll(this, 'onAdReady', 'showAd', 'onResize');

            // call base class initialize
            OverlayAdBase.prototype.initialize.call(this, options);

            this.loadAdPlacement();

            AdLogger.logDebug('Partner Shared Overlay initialized', this);
        },

        loadAdPlacement: function() {
            this.subviews.ad = new SharedAdPosition({
                el: this.$placement,
                adSizes: this.options.adSizes,
                adPlacement: this.options.adPlacement,
                adType: this.options.adType,
                onAdReady: this.onAdReady,
                beforeAdRender: this.onResize
            });
        },

        onAdReady: function(adInfo) {
            if (adInfo.leaveBehindImage && adInfo.leaveBehindText && this.options.leaveBehindEl) {
                this.subviews.adLeaveBehind = new LeaveBehind({
                    el: this.options.leaveBehindEl,
                    onShowAd: this.showAd,
                    imageUrl: adInfo.leaveBehindImage,
                    altText: adInfo.leaveBehindText,
                    isCompact: this.options.isCardBumped,
                    isStagFront: this.options.isStagFront
                });
                this.subviews.adLeaveBehind.render(this.subviews.ad);
            } else {
                this.showAd();
            }
        },
        close: function() {
            if (this.subviews.adLeaveBehind) {
                this.subviews.adLeaveBehind.show();
            }
            OverlayAdBase.prototype.close.apply(this, arguments);
        }
    });

    return OverlaySharedAd;
});

/**
 * @fileoverview Cards View.
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/modules/cards2',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'appview',
    'baseappview',
    'views/modules/partner/pushdown-ad',
    'views/modules/partner/overlay-ad-fronts',
    'state',
    'libs/onlineopinion/oo_engine'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    AppView,
    BaseAppView,
    PushdownAd,
    OverlayAdFront,
    StateManager,
    OOo
){
    
        /**
         * View class.
         */
        
        var CardView = BaseAppView.extend({
            // View element.
            el: '#cards',

            events: {
                'click .open-sidebar': 'openSidebar',
                'click .close-sidebar': 'closeSidebar',
                'click .feedback': 'openFeedback'
            },

            // Instance variables
            cards: [
                'home',
                'news',
                'sports',
                'life',
                'money',
                'tech',
                'travel',
                'opinion',
                'weather'
            ],

            cardSizes : [
                {
                    name: 'large',
                    adClass: 'size-l',
                    sidebarAds: true,
                    belowHeroAd: false,
                    cardWidth: 1180,
                    windowWidth: 1250
                },
                {
                    name: 'medium',
                    adClass: 'size-m',
                    sidebarAds: false,
                    belowHeroAd: true,
                    cardWidth: 1080,
                    windowWidth: 1150
                },
                {
                    name: 'small',
                    adClass: 'size-s',
                    sidebarAds: false,
                    belowHeroAd: true,
                    cardWidth: 840,
                    windowWidth: 980
                }
            ],

            initialize: function(options){
                options = $.extend(true, {
                    animations: {
                        horizontal: {
                            duration: 350,
                            easing: 'cubic-bezier(0.645, 0.045, 0.355, 1.000)'
                        },
                        fadeIn: {
                            duration: 200
                        },
                        sidebar: {
                            button: {
                                fadeIn: 200,
                                fadeOut: 200
                            },
                            slide: 250
                        }
                    },
                    UPDATE_FREQUENCY: 900000, // Time in ms before checking for new data.
                    keyboard: false,
                    peekWidth: -100,
                    minCardWrapWidth: 1024 - 120,
                    template:
                        '<section class="card-wrap">' +
                            '<section class="card <%= section %> card-loading" id="section_<%= section %>">' +
                                '<div class="left-suspender size-suspender">' +
                                    '<div class="mod clst sections navigation" id="CList-sections"><h1 class="clst-section-name"><%= section %></h1></div>' +
                                '</div>' +
                                '<div class="border">' +
                                    '<div class="punchout-cover"></div>' +
                                '</div>' +
                            '</section>' +
                        '</section>',
                    overlayTemplate:
                        '<section class="card-wrap">' +
                            '<section class="card <%= section %> card-loading" id="section_<%= section %>">' +
                                '<div class="left-suspender size-suspender"></div>' +
                                '<div class="border"></div>' +
                                '<div class="size-bar paper-shade">' +
                                    '<div class="mod live-feed"></div>' +
                                '</div>' +
                            '</section>' +
                        '</section>'
                }, options);

                _.bindAll(this, 'handleResizeWindow', 'showSidebarOpenButton', 'showSidebarCloseButton');

                this.$top = App.get('scrollEl');
                this.$doc = App.get('doc');
                this.$window = App.get('win');
                this.template = _.template(options.template);
                this.overlayTemplate = _.template(options.overlayTemplate);
                this.containerOffset = 0;
                this.header = AppView.getHeader();

                this.pubSub = {
                    'sidebar:button:hide': this.hideSidebarOpenButton,
                    'sidebar:button:show': this.delayShowSidebarOpenButton,
                    'sidebar:hide': this.closeSidebar,
                    'sidebar:show': this.openSidebar
                };
                var throttledResize = _.throttle(this.handleResizeWindow, 50);
                this.$window.on('resize.' + this.cid, throttledResize);
                if (this.options.keyboard){
                    // Keyboard navigation.
                    this.$doc.on('keydown.' + this.cid, this.keyNavigation);
                }
                this.topAdjusted = false;
                this.domInitialized = false;

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);

                this.calculateCardDimensions(this.$window.width());
                this.isSidebarOpen = !this.isMinCardWidth();
            },

            openFeedback: function(){
                (new OOo.Ocode({})).show();
            },

            destroy: function(removeEl){
                this.$window.off('.' + this.cid);
                this.$doc.off('.' + this.cid);

                // call base class destroy
                BaseAppView.prototype.destroy.call(this, removeEl);
            },

            animateChangePagePreData: function(fromPath, toPath){
                var sectionName = App.getSectionPath(toPath);
                var promise = this.goTo(sectionName);
                this._updateNav(toPath);
                if (!promise && this.currentPath !== toPath){
                    var $blankCard = this.createAndInitializeEmptyCard(sectionName);
                    $blankCard.css({position: 'relative', margin: '', left: this.containerOffset * -1});
                    this.$currentCard.css({left: this.leftMargin + this.containerOffset * -1});
                    promise = this.swapContent(this.$currentCard, $blankCard);
                    this.$currentCard = $blankCard;
                }
                return promise;
            },
            animateChangePagePostData: function(fromPath, toPath, htmlFrag, paused) {
                // current card should be the loader we want to swap out
                var currentCard = this.$currentCard,
                    newCard = htmlFrag.find('.card-wrap');
                newCard.css({left: this.containerOffset * -1});
                if (newCard.find('.hero.bump').length) {
                    currentCard.find('.punchout-cover').addClass('show');
                }
                currentCard.css({height: '', overflow: '', 'padding-right': '', left: this.leftMargin + this.containerOffset * -1});
                // move the current card pointer incase someone navigates while swapContent is happening
                this.$currentCard = newCard;
                return this.swapContent(currentCard, newCard);
            },
            animateRevealApp: function(fromPath, toPath, preload){
                this._updateNav(toPath);
                if (preload) {
                    this.afterOverlayReveal(StateManager.getBreakingNewsOffset());
                    return $.Deferred().resolve();
                } else {
                    return BaseAppView.prototype.animateRevealApp.apply(this, arguments);
                }
            },
            beforePageReveal: function(fromPath, toPath, htmlFrag, preload){
                if (preload){
                    // hide the preload, we have our own temporary cards shown
                    htmlFrag.css('display', 'none');
                }
                App.set('currentCardPath', toPath);
            },
            afterPageReveal: function(fromPath, toPath, paused, ViewClass){
                var sectionName = App.getSectionPath(toPath);
                if (!this.domInitialized){
                    this.initializeDom();
                    this._updateNav(toPath);
                }
                this.$currentCard = this.$container.children('.card-wrap');
                this.currentIndex = _.indexOf(this.cards, sectionName);

                // Add sidebar to new card.
                this.addSidebar();

                if (!paused){
                    if (ViewClass){
                        this.subviews.view = new ViewClass({el: this.$currentCard, path: toPath, section: sectionName});
                        this.subviews.view.render(this.currentCardInfo);
                    }
                    if (this.isSidebarOpen){
                        this.onSidebarOpen();
                    }
                    this.subviews.pushdownAd = new PushdownAd({
                        el: this.$currentCard,
                        adClasses: _.pluck(this.cardSizes, 'adClass').join(' ')
                    });
                    this.subviews.pushdownAd.render(this.currentCardInfo, this.isCurrentCardBumped());
                    this.subviews.overlayAd = new OverlayAdFront({
                        el: this.$('.partner-overlay'),
                        leaveBehindEl: this.$('.partner-leavebehind'),
                        isCardBumped: this.isCurrentCardBumped()
                    });
                }

                PubSub.trigger('cards:loaded');
            },
            isCurrentCardBumped: function() {
                return this.$currentCard.children('.card-bumped').length;
            },
            beforeAppRemove: function(fromPath, toPath){
                $('#nav > ul .text').removeClass('active');
            },
            getRevealAppLoader: function(toPath){
                var sectionName = App.getSectionPath(toPath);
                this._updateNav(toPath);
                var temp = $(this.template({section: sectionName}));
                temp = $('<div class="card-container"></div>').append(temp);
                temp = $('<article id="cards" class="cards"></article>').append(temp);
                return temp;
            },
            activateLoader: function(){
                // we have our own custom loader, no need for the system loader
            },

            initializeDom: function(){
                // Cache selectors
                this.$container = this.$('.card-container');
                this.$prevBtn = this.$('#cards-prev-link');
                this.$nextBtn = this.$('#cards-next-link');

                this.domInitialized = true;
            },

            handleResizeWindow: function(){                
                if (this.domInitialized){
                    var windowWidth = this.$window.width();
                    if (this.windowWidth === windowWidth){
                        return false;
                    }                    
                    var oldCardInfo = this.currentCardInfo;
                    this.calculateCardDimensions(windowWidth);
                    if (this.currentCardInfo !== oldCardInfo) {
                        // card sizing has changed
                        // so pass in whether we're destroying sidebar, or creating the sidebar
                        // (ie, going to min card width, or going from min card width
                        this.resetSidebar(this.isMinCardWidth() || oldCardInfo === this.getMinCardInfo());
                        this.triggerEvent('onCardWidthChange', this.currentCardInfo);
                    }
                }
            },

            calculateCardDimensions: function(windowWidth){
                var minSize = this.getMinCardInfo();
                if (windowWidth < minSize.windowWidth){
                    windowWidth = minSize.windowWidth;
                }
                this.windowWidth = windowWidth;
                var cardInfo = minSize;
                // IE is a bastard, I hate it. IE8 reports media query, but it doesn't work for min-width
                var mediaQuery = (window.matchMedia || Modernizr.mq('only all')) && !this.$top.hasClass('lt-ie9');

                _.find(this.cardSizes, function(item) {
                    if (mediaQuery){
                        // media query standard browsers report the width including the scrollbar
                        // but $window.width() reports minus scrollbar, so this makes certain our cardWidth
                        // is accurate
                        if (Modernizr.mq('only screen and (min-width: ' + item.windowWidth + 'px)')) {
                            cardInfo = item;
                            return true;
                        }
                    }else{
                        if (windowWidth >= item.windowWidth) {
                            cardInfo = item;
                            return true;
                        }
                    }
                });
                this.cardWrapWidth = cardInfo.cardWidth + ((windowWidth - 2 * this.options.peekWidth - cardInfo.cardWidth) / 2 + 0.5) >> 0;
                if (this.cardWrapWidth < this.options.minCardWrapWidth){
                    this.cardWrapWidth = this.options.minCardWrapWidth;
                }
                this.leftMargin = (((windowWidth - cardInfo.cardWidth - 2 * this.options.peekWidth) / 2) +
                    this.options.peekWidth + 0.5) >> 0; // round up
                this.currentCardInfo = cardInfo;
                return cardInfo;
            },

            /**
             * Compare a time string with the current datetime. If it
             * @param {String} timeStr The time string to compare with.
             * @param {String} compareWith Timestamp to compare with.
             * @return {Boolean} Returns true if timeStr is new.
             */
            compareTime: function(timeStr, compareWith) {
                var timeNow = (new Date()).getTime();
                var timeThen = parseInt(timeStr, 10) * 1000; // get it to ms.
                return ((timeNow - timeThen) > compareWith);
            },

            updateNavLinks: function(btn, href) {
                href = (href === 'home') ? '/' : '/' + href + '/';
                btn.attr('href', href);
            },

            /**
             * Keyboard navigation (left / right arrows).
             * @param {Event} e Keyboard event.
             */
            keyNavigation: function(e) {
                switch(e.keyCode) {
                    // Left arrow.
                    case 37:
                        this.previous();
                        break;
                    // Right arrow.
                    case 39:
                        this.next();
                        break;
                    default:
                        break;
                }
            },

            /**
             * Check if index is a) numeric and b) within bounds.
             * @param {Number} n Number to compare.
             * @param {Number} l Max length.
             */
            inBounds: function(n, l) {
                return (!isNaN(parseFloat(n, 10)) &&
                    isFinite(n) && n >= 0 && n <= (l - 1));
            },

            /**
             * Animate to a card.
             * @param {String} targetId The id of the target card.
             */
            goTo: function(targetId) {
                // Target index.
                var targetIndex = _.indexOf(this.cards, targetId);

                // Check the bounds.
                if(targetIndex === -1 || targetIndex === this.currentIndex) {
                    return;
                }

                var scrollPosition = App.getScrollPosition();

                if (this.isApple && scrollPosition > 0){
                    // iOS devices can't do the fancy scroll trick we do to trick the user
                    // into not believing they aren't scrolling to the top of the window when they
                    // actually are. So we need to animate the scroll to the top
                    return $.Deferred(_.bind(function(defer){
                        this.$top.animate({scrollTop: 0}, 200).promise().done(_.bind(function(){
                            this._animateCards(targetIndex, scrollPosition).done(function(){
                                defer.resolve();
                            });
                        }, this));
                    })).promise();
                }else{
                    return this._animateCards(targetIndex, scrollPosition);
                }
            },

            _animateCards: function(targetIndex, scrollPosition) {
                // Ready to animate.
                var nextCard, indexPeek, distance = 0, tempCardList = $([]),
                    height = this.$window.height(),
                    currentCard = this.$currentCard,
                    direction = 0;

                // pick a direction
                if (Math.abs(targetIndex - this.currentIndex) > (this.cards.length / 2)) {
                    // flip around
                    direction = targetIndex > this.currentIndex ? -1 : 1;
                } else {
                    direction = targetIndex > this.currentIndex ? 1 : -1;
                }
                // create temporary cards
                do {
                    this.currentIndex = this._incrementIndex(this.currentIndex, direction);
                    nextCard = this.createAndInitializeEmptyCard(this.cards[this.currentIndex]);
                    if (this.currentIndex !== targetIndex) {
                        tempCardList.push(nextCard[0]);
                    }
                    nextCard.css({height: height});
                    this._positionCard(nextCard, (++distance) * direction);
                    this.$container.append(nextCard);
                } while (this.currentIndex !== targetIndex);
                // reset internal variables
                this.$currentCard = nextCard;
                this.containerOffset -= distance * direction * this.cardWrapWidth;

                currentCard.css({height: height, 'overflow': 'hidden', 'padding-right': '20px'});

                // fake scroll to top
                if (!this.isApple) {
                    if (scrollPosition > 0) {
                        // non-iOS devices can do our scrolling trick by faking the top of the current card after a scrollTop(0)
                        this.$top.scrollTop(0);
                        currentCard.children('.card').css({top: -1 * scrollPosition});
                    }
                }

                var promise = this.animate(this.$container,
                                            'left',
                                            this.containerOffset + 'px',
                                            this.options.animations.horizontal.duration,
                                            this.options.animations.horizontal.easing);
                promise.done(function() {
                    currentCard.remove();
                    tempCardList.remove(); // remove temp cards
                    nextCard.css('position', 'relative');
                });
                return promise;
            },

            _incrementIndex: function(index, amount) {
                return (this.cards.length + index + amount) % this.cards.length;
            },

            createAndInitializeEmptyCard: function(section){
                var $blankCard = $(this.template({section: section}));
                $blankCard.css({'margin': 0, position: 'absolute', bottom: 0});
                return $blankCard;
            },

            _positionCard: function(targetDom, targetPosition){
                targetDom.css({left: (this.leftMargin - this.containerOffset + (targetPosition * this.cardWrapWidth))});
            },

            /**
             * Add sidebar
             */
            addSidebar: function() {
                this.sidebar = this.$currentCard.find('.size-bar');
                this.sidebarOpenButton = this.$currentCard.find('.open-sidebar');
                this.sidebarCloseButton = this.$currentCard.find('.close-sidebar');
            },
            /**
             * Slides the panel out from behind the page card.
             */
            openSidebar: function(event) {
                if (event){
                    event.preventDefault();
                    event.stopPropagation();
                }

                this.onSidebarOpen();

                this._slideSidebar(this.sidebarOpenButton, true);
            },

            onSidebarOpen: function(){
                if (this.subviews.view && this.subviews.view.renderExpanded){
                    this.subviews.view.renderExpanded(this.currentCardInfo);
                }
                this.isSidebarOpen = true;
            },

            /**
             * Slides the sidebar behind the page card.
             */
            closeSidebar: function(event) {
                if (event){
                    event.preventDefault();
                    event.stopPropagation();
                }

                var animation = this._slideSidebar(this.sidebarCloseButton, false);
                this.onSidebarClose(animation);
            },

            onSidebarClose: function(animationPromise){
                this.isSidebarOpen = false;
                if (this.subviews.view && this.subviews.view.destroyExpanded) {
                    if (animationPromise) {
                        animationPromise.done(_.bind(function(){
                            this.subviews.view.destroyExpanded(true);
                        }, this));
                    } else {
                        this.subviews.view.destroyExpanded(true);
                    }
                }
            },

            _slideSidebar: function(button, open){
                var slideSpeed = this.options.animations.sidebar.slide;
                var fadeSpeed = this.options.animations.sidebar.button.fadeOut;

                this.registerAnimation(button.fadeOut(fadeSpeed, 'easeInOutCubic').promise());

                var w = parseInt(this.sidebar.css('width'), 10);

                var slideAnimation = null;
                if (this.isMinCardWidth()){
                    slideAnimation = this.animate(this.sidebar, 'right', -(w)+'px', slideSpeed, 'ease-in-out');
                } else {
                    var cardInfo = open ? this.currentCardInfo : this.getMinCardInfo();
                    this.sidebar.removeClass('top');
                    slideAnimation = this.animate(this.$currentCard.children('.card'), 'width', cardInfo.cardWidth, slideSpeed, 'ease-in-out');
                }
                var deferred = $.Deferred();
                slideAnimation.done(_.bind(function() {
                    var slideAnimation = this.animate(this.sidebar, 'right', 0, slideSpeed, 'ease-in-out');
                    if (open){
                        if (this.isMinCardWidth()){
                            this.sidebar.addClass('top');
                            slideAnimation.done(this.showSidebarCloseButton);
                        }else{
                            this.sidebar.removeClass('top');
                            this.$currentCard.css('width', '');
                        }
                    }else{
                        slideAnimation.done(this.showSidebarOpenButton);
                        this.sidebar.removeClass('top');
                    }
                    slideAnimation.done(function(){
                        deferred.resolve();
                    });
                }, this));
                return deferred.promise();
            },

            isMinCardWidth: function() {
                return this.currentCardInfo === this.getMinCardInfo();
            },

            getMinCardInfo: function() {
                return this.cardSizes[this.cardSizes.length - 1];
            },

            /**
             * Recalculate and reset screen width for sidebar
             */
            resetSidebar: function(sidebarStatusChange) {
                this.$currentCard.css('width', '');
                this.sidebar.removeClass('top');
                if (this.isMinCardWidth()){
                    if (!$('.partner-heroflip-ad').hasClass('active')) {
                        this.sidebarOpenButton.show();
                    }
                    this.sidebarCloseButton.hide();
                    if (sidebarStatusChange){
                        this.onSidebarClose();
                    }
                }else{
                    this.sidebarOpenButton.hide();
                    this.sidebarCloseButton.show();
                    if (sidebarStatusChange){
                        this.onSidebarOpen();
                    }
                }
            },
            /**
             * Show the sidebar open button.
             */
            showSidebarOpenButton: function(adCall) {
                if (this.adVisible && !adCall) return false;
                if (!$('.partner-heroflip-ad').hasClass('active')) {
                    this.sidebarOpenButton.css({'visibility': 'visible', display: 'none'});
                    this.sidebarOpenButton.fadeIn(this.options.animations.sidebar.button.fadeIn, 'easeInOutCubic');    
                }
                if (adCall) this.adVisible = false;
            },

            /**
             * Show the sidebar close button.
             */
            showSidebarCloseButton: function() {
                this.sidebarCloseButton.fadeIn(this.options.animations.sidebar.button.fadeIn, 'easeInOutCubic');
            },

            delayShowSidebarOpenButton: function(adCall) {
                _.delay(_.bind(function() {
                    if (this.isMinCardWidth()){
                        this.showSidebarOpenButton(adCall);
                    }
                }, this), 1000);
            },

            hideSidebarOpenButton: function(adCall) {
                if (adCall) this.adVisible = true;
                this.sidebarOpenButton.fadeOut(this.options.animations.sidebar.button.fadeOut, 'easeInOutCubic');
            },

            /**
             * Hide the fixed cards behind the overlay to improve scroll performance.
             */
            afterOverlayReveal: function(offset) {
                this.$el.hide();

                var activeDom = StateManager.getActiveApp().$el;
                var currentSection = App.getSectionPath(this.currentPath);
                var offsetPlaceholder = '<div id="cards-offset-placeholder" style="top:' + offset + 'px;"></div>';
                var emptyCard = this.overlayTemplate({ section: currentSection });
                activeDom.append(offsetPlaceholder + emptyCard);
            },

            /**
             * Show the fixed cards again (and remove the temporary ones).
             */
            beforeOverlayRemove: function(toPath) {
                this.$el.show();

                var activeDom = StateManager.getActiveApp().$el;
                activeDom.find('#cards-offset-placeholder').css('display', 'none');
                activeDom.find('.card-wrap').css('display', 'none');
                this._updateNav(toPath);
            },

            /**
             * Adds card size information to page ad requests
             * @override
             */
            getClientAdInfo: function() {
                return {cardsize: this.currentCardInfo.name};
            },

            _updateNav: function(toPath) {
                this.header.updateNavigation(toPath);
                var section = App.getSectionPath(toPath);

                var currentIndex = _.indexOf(this.cards, section);

                if (this.domInitialized){
                    this.updateNavLinks(this.$prevBtn, this.cards[this._incrementIndex(currentIndex, -1)]);
                    this.updateNavLinks(this.$nextBtn, this.cards[this._incrementIndex(currentIndex, 1)]);
                }                
            }

        });

        /**
         * Return view class.
         */
        return CardView;
    }
);
/**
 * @fileoverview SidebarScroll.
 * Extends Vertical Scroll for treatment on Sidebars on cards
 * @author mdkennedy@gannett.com (Mark Kennedy)
 */
 define('views/modules/scroller/sidebar-scroll',[
    'jquery', 
    'underscore', 
    'views/modules/scroller/vertical-scroll'
],
function(
    $, 
    _, 
    VerticalScroll
)
    {

        /**
         * View class.
         */
        var SidebarScroll = VerticalScroll.extend({

            initialize: function(options) {
                _.bindAll(this,
                    'onScrollUpdated',
                    'removeActiveClass');

                options = $.extend({
                    removeActiveDelay: 700 // ms until scrollbar fades away
                }, options);

                if (Modernizr.touch) {
                    this.$el.css({'-webkit-overflow-scrolling': 'touch'});
                    if (this.$el.css('-webkit-overflow-scrolling') === 'touch'){
                        // if the device supports touch, and -webkit-overflow-scrolling, use the native scroller
                        this.$el.css({'overflow': 'scroll'});
                        options.disabled = true;
                    }
                }
                this.addBottomShadow();
                this.addTopShadow();

                VerticalScroll.prototype.initialize.call(this, options);

                // by default hide the bar
                this.bar.addClass('hide');
            },

            /**
             * Bind events.
             */
            bindEvents: function() {
                if (!this.options.disabled){
                    this.$el.on('scrollBarUpdate.' + this.cid, this.onScrollUpdated);
                    VerticalScroll.prototype.bindEvents.apply(this, arguments);
                }
            },

            destroy: function(removeEl){
                this.$el.off('.' + this.cid);
                this.bar.remove();
                this.topShadow.remove();
                this.bottomShadow.remove();
                clearTimeout(this.removeActiveClassDelay);
                clearTimeout(this.hideClassDelay);
                VerticalScroll.prototype.destroy.apply(this, arguments);
            },

            addTopShadow: function() {
                this.topShadow = $('<div class="shadow top-shadow"></div>').hide();
                this.$el.append(this.topShadow);
            },

            /**
             * Add shadow to bottom of scroll content
             */
            addBottomShadow: function() {
                this.bottomShadow = $('<div class="shadow bottom-shadow"></div>').hide();
                this.$el.append(this.bottomShadow);
            },

            /**
             * Remove active class.
             */
            removeActiveClass: function() {
                if(this.isMouseDown || this.isMouseOver){
                    return;
                }
                this.bar.removeClass('active');
                clearTimeout(this.removeActiveClassDelay);
                this.hideClassDelay = setTimeout(_.bind(function() {
                    this.bar.addClass('hide');
                }, this), 1000);
            },

            /**
             * Add active class.
             */
            addActiveClass: function(delay) {
                this.bar.addClass('active');
                this.bar.removeClass('hide');
                this.startTimeout(delay || this.options.removeActiveDelay);
            },

            /**
             * Add active class.
             */
            startTimeout: function(delay) {
                clearTimeout(this.removeActiveClassDelay);
                this.removeActiveClassDelay = setTimeout(this.removeActiveClass, delay);
            },

            onMouseOut: function(){
                VerticalScroll.prototype.onMouseOut.apply(this, arguments);
                if(!this.isMouseDown) {
                    this.startTimeout(this.options.removeActiveDelay);
                }
            },

             /**
             * Add active scroll.
             */
            onMouseEnter: function(){
                VerticalScroll.prototype.onMouseEnter.apply(this, arguments);
                this.addActiveClass(this.options.removeActiveDelay);
            },

            /**
             * When the scrollbar position is updated.
             */
            
            onScrollUpdated: function(e, percent) {
                if (percent === 0) {
                    this.topShadow.hide();
                } else {
                    this.topShadow.show();
                }

                if(percent === 1) {
                    this.bottomShadow.hide();
                } else {
                    this.bottomShadow.show();
                }

                this.addActiveClass();
            }

        });


        /**
         * Return view class.
         */
        return SidebarScroll;
    }
);
/**
 * @fileoverview Live feed view module.
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
define('views/modules/live-feed-view',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'app',
    'sharedAdPosition',
    'views/modules/scroller/sidebar-scroll'
],
function(
    $,
    _,
    BaseView,
    StateManager,
    App,
    SharedAdPosition,
    SidebarScroll
)
    {
        
        /**
         * View class.
         */
        var LiveFeedView = BaseView.extend({

            /**
             * Initialize view.
             */
            initialize: function(options) {
                _.bindAll(this,
                    'refreshMarkup',
                    'refreshScrollBar',
                    'initMarkup',
                    'fetchUpdate',
                    'onAdReady'
                );

                options = $.extend({
                    maxItems: 60,
                    ads: false, // whether or not an ad is possible to be shown, used to decide when to reset the top css to 0
                    // this is when the highlights to new content gets removed - should be less than updateDelay
                    removeNewHighlight: 20, // seconds
                    updateDelay: 30, // seconds
                    dataSrcAttr: 'data-src'
                }, options);

                options.section = this.$el.attr('data-livefeed') || options.section;

                this.win = App.get('win');
                this.body = App.get('body');
                this.pubSub = {
                    'showmore:headlines': this.onHeadlinesUpdated
                };

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);

                // clear the el top in case an ad used to be showing after we close an overlay
                this.onHideSidebarAd();
            },

            onAdReady: function() {
                this.subviews.ad.showAd();
                this.$el.css('top', this.subviews.ad.getHeight());
                this.$el.addClass('ad-above');
                this.refreshScrollBar();
            },

            onHideSidebarAd: function() {
                if (this.subviews.ad) {
                    this.subviews.ad.destroy(true);
                    this.subviews.ad = null;
                }
                this.$el.css('top', 0);
                this.$el.removeClass('ad-above');
                this.refreshScrollBar();
            },

            loadLazyImages: function(images) {
                images = images || this.$('img');
                App.lazyLoadImage(images, this.options.dataSrcAttr, true, this.hideBrokenHasImage);

            },

            render: function(currentCardInfo) {
                this.$ul = this.$('ul');
                this.setLiveFeedWidth(currentCardInfo);

                // Initialize the vertical scroll
                this.subviews.vscrollbar = new SidebarScroll({
                    el: this.$('.live-feed-content'),
                    color: this.options.color,
                    padding: 2,
                    lockPageScroll: false,
                    delayScroll: false,
                    fadeout: true
                });

                if (this.$ul.find('li').length) {
                    this.subviews.vscrollbar.moveDraggerToPosition(0, 0);
                    // remove the new content class that might not be removed, cleanup just in case
                    this.$ul.children('.newcontent').removeClass('newcontent');
                    this.fetchUpdate();
                } else {
                    this.$el.addClass('loading');
                    this.fetchData('/feeds/live/' + this.options.section + '/?count=40', this.initMarkup);
                }
                this.startUpdateCheck();
                if (currentCardInfo.sidebarAds) {
                    this.subviews.ad = new SharedAdPosition({
                        el: this.$el.siblings('.partner-sidebar-ad'),
                        adSizes: ['mediumrectangle', 'halfpage', 'livefeed'],
                        adPlacement: 'high_impact',
                        adType: 'sidebar',
                        defaultPosition: true,
                        onAdReady: this.onAdReady
                    });
                    this.$el.closest('.card-container').find('.below-hero-ad').remove();
                }
            },

            /**
             * Checks for updated data for specified section.
             */
            fetchUpdate: function() {
                var timestamp = this.$ul.find('li:first').attr('data-timestamp');

                // uncomment for testing livefeed - remove before launch
                // if(this.debug) {
                //  //this.debug = false;
                // timestamp = '2012-09-11T03:32:33';
                //  }
                //  else {
                //  return;
                //  }

                var url = '/feeds/live/' + this.options.section + '/?date=' + timestamp;
                this.fetchData(url, this.refreshMarkup);
            },

            /**
             * Loads initial live feed data for specified section.
             * @param {String} url path to be loaded.
             * @param {Function} callback function to be called when successful.
             */
            fetchData: function(url, callback) {
                StateManager.fetchHtml(url)
                    .done(callback)
                    .always(_.bind(function() {
                        this.$el.removeClass('loading');
                    }, this));
            },

            /**
             * Handler for when additional data is loaded.
             * Prepends new items to the live feed list.
             * @param {String} newMarkup markup from ajax request.
             */
            refreshMarkup: function(newMarkup) {
                if (!newMarkup || newMarkup.length === 0) return;
                var $li = this.$ul.find('li'),
                    contentIdMap = {},
                    $this;
                // take off the current top class, new content will get the top class
                $li.removeClass('top');

                newMarkup.each(function() {
                    contentIdMap[$(this).attr('data-content-id')] = true;
                });
                // If a duplicate is in the new markup, remove the existing one from the DOM.
                $li.each(function() {
                    $this = $(this);
                    if (contentIdMap[$this.attr('data-content-id')]) {
                        $this.remove();
                    }
                });

                // Prepend all new items.
                newMarkup.eq(0).addClass('top').append('<div class="shadow"></div>');
                this.$ul.prepend(newMarkup);

                // Show updates to new content, etc.
                newMarkup.addClass('newcontent');
                this.loadLazyImages(newMarkup.find('img'));
                $li = this.$ul.children('li');
                // If there are over 60 items remove oldest.
                if ($li.length > 60) {
                    $li.slice(60).remove();
                }

                this.refreshScrollBar();

                this.afterNewContent = setTimeout(_.bind(function() {
                    newMarkup.removeClass('newcontent');
                }, this), this.options.removeNewHighlight * 1000);
            },

            /**
             * Handler initial data loaded only.
             * @param {Object} markup list of li's that will be added to the ul.
             */
            initMarkup: function(markup) {
                this.$ul.append(markup);
                this.loadLazyImages(markup.find('img'));
                this.refreshScrollBar();
                this.startUpdateCheck();
            },

            /**
             * Called when the page resizes as when the media query changes
             * the width of the panel we need to refresh the scrollbar.
             */
            refreshScrollBar: function() {
                if (this.subviews && this.subviews.vscrollbar) {
                    this.subviews.vscrollbar.refresh();
                }
            },

            onCardWidthChange: function(cardWidthInfo) {
                this.setLiveFeedWidth(cardWidthInfo);
                this.loadLazyImages();
                this.refreshScrollBar();
            },

            /**
            * Used to change/set the live feed width, sets the this.options.dataSrcAttr option
            * and the live-feed-width class on the ul
            * @param {{name: String}} cardWidthInfo card width info object with a name we can key off of
            */
            setLiveFeedWidth: function(cardWidthInfo) {
                var dataSrcAttr = 'data-src',
                    cardWidth = 'small';
                if(cardWidthInfo){
                    cardWidth = cardWidthInfo.name;
                }
                this.$ul.removeClass('live-feed-wide');
                if (cardWidth === 'large') {
                    dataSrcAttr = 'data-src-large';
                    this.$ul.addClass('live-feed-wide');
                } else {
                    this.$ul.removeClass('live-feed-wide');
                }
                this.options.dataSrcAttr = dataSrcAttr;
            },

            /**
             * Called when the page height changes due to more stories loading.
             * 1 second is an arbitrary wait time to allow height transition to complete.
             */
            onHeadlinesUpdated: function() {
                this.headlinesUpdate = setTimeout(this.refreshScrollBar, 1000);
            },

            /**
             * Starts the update check.
             */
            startUpdateCheck: function() {
                clearInterval(this.interval);
                this.interval = setInterval(this.fetchUpdate, this.options.updateDelay * 1000);
            },

            /**
             * Stops the update check.
             */
            stopUpdateCheck: function() {
                clearInterval(this.interval);
            },

            /**
             * Broken image error function
             * finds and removes closest has-image class to switch layout to none image styles
             */
            hideBrokenHasImage: function() {
                $(this).closest('.has-image').removeClass('has-image');
            },

            /**
             * Clean up the view (no argument).
             */
            destroy: function(removeEl) {
                this.$el.removeClass('loading');
                this.stopUpdateCheck();
                clearTimeout(this.afterNewContent);
                clearTimeout(this.headlinesUpdate);

                // this is kind of a hack, we don't want to remove the entire element, cause we
                // can't come back to life, instead we just want to empty the ul list
                if (removeEl) {
                    this.$ul.empty();
                }

                // call base class initialize
                BaseView.prototype.destroy.call(this, false);
            }

        });


        /**
         * Return view class.
         */
        return LiveFeedView;
    }
);

(function($) {
    
    var dataName = 'uiPageTurn';
    var defaults = {
        useTransforms: !!$.support.css.transform,
        fallback: 'crossfade', // or 'slide'
        pageSelector: '.ui-page-turn',
        placerSelector: '.ui-placer',
        transitionTiming: 'linear',
        turnDuration: 300,
        perspective: '2200px',
        slideDuration: 200,
        fadeDuration: 200,
        shadow: true,
        shadowOpacity: 0.7,

        onPageTurn: function($el){}
    };

    var methods = {
        init : function(options){
            return this.each(function(){
                var $this = $(this);
                var settings = $.extend({}, defaults, options);
                var $currentPage = $this.find(settings.pageSelector + '.active');
                if ($currentPage.length === 0){
                    $currentPage = $this.children(':first');
                }
                $currentPage.next(settings.pageSelector).addClass('preload');
                $this.data(dataName, {
                    currentPage: $currentPage,
                    busy: false,
                    settings: settings
                });
            });
        },
        option: function(key, value){
            var data = this.data(dataName);
            if (data && key){
                if (value){
                    if (typeof(value) === 'function' ||
                        key !== 'onPageTurn'
                        ){
                        data[key] = value;
                    }
                }else{
                    return data[key];
                }
            }
        },
        nextPage: function(immediate) {
            var data = this.data(dataName),
                settings = data.settings,
                $currentPage = data.currentPage,
                $nextPage = $currentPage.next(settings.pageSelector);
            return privateMethods.transition(this, $currentPage, $nextPage, false, settings, data, immediate);
        },
        prevPage: function(immediate) {
            var data = this.data(dataName),
                settings = data.settings,
                $currentPage = data.currentPage,
                $prevPage = $currentPage.prev(settings.pageSelector);
            return privateMethods.transition(this, $currentPage, $prevPage, true, settings, data, immediate);
        },
        goToPage: function(index, immediate){
            var data = this.data(dataName),
                settings = data.settings,
                $currentPage = data.currentPage,
                $nextPage = this.children(settings.pageSelector).eq(index),
                currentIndex = $currentPage.index(settings.pageSelector);
            if (currentIndex === index){ return $.Deferred().reject(); }
            return privateMethods.transition(this, $currentPage, $nextPage, currentIndex > index, settings, data, immediate);
        },
        getCurrentPage: function(){
            var data = this.data(dataName);
            return data.currentPage;
        }
    };

    var privateMethods = {
        transition: function($el, $currentPage, $nextPage, leftToRight, settings, data, immediate){
            var promise;
            if (!$nextPage.length || data.busy) {return $.Deferred().reject();}

            if (immediate) {
                privateMethods.finishTransition($currentPage, $nextPage, leftToRight, settings, data);
                return $.Deferred().resolve();
            }
            data.busy = true;

            $nextPage.removeClass('preload');

            if (settings.useTransforms){
                promise = privateMethods.flipTransform($el, $currentPage, $nextPage, leftToRight, settings);
            }else if (settings.fallback === 'slide'){
                promise = privateMethods.slideTransition($currentPage, $nextPage, leftToRight, settings);
            }else{
                promise = privateMethods.fadeTransition($currentPage, $nextPage, settings);
            }
            promise.done(function(){
                privateMethods.finishTransition($currentPage, $nextPage, leftToRight, settings, data);
            });
            return promise;
        },
        finishTransition: function($currentPage, $nextPage, leftToRight, settings, data) {
            settings.onPageTurn($nextPage);
            data.busy = false;
            $currentPage.removeClass('active');
            $nextPage.addClass('active');
            if (leftToRight) {
                $nextPage.prev(settings.pageSelector).addClass('preload');
            } else {
                $nextPage.next(settings.pageSelector).addClass('preload');
            }
            data.currentPage = $nextPage;
        },
        flipTransform: function($el, $currentPage, $nextPage, leftToRight, settings){
            $currentPage.removeClass('active');

            var $currentAnimator = $currentPage.clone(),
                $nextAnimator = $nextPage.clone(),
                $beforeShadow = $('<div class="ui-shadow"></div>'),
                $afterShadow = $('<div class="ui-shadow"></div>'),
                $animatorWrap = $('<div class="ui-page-turn-animator"></div>');

            if (settings.shadow) {
                $nextPage.append($beforeShadow);
                $currentPage.append($afterShadow);
                $beforeShadow.css({opacity: settings.shadowOpacity});
                $afterShadow.css({opacity: 0});
            }

            $animatorWrap.append($currentAnimator);
            $animatorWrap.append($nextAnimator);
            $el.append($animatorWrap);
            if (leftToRight){
                $currentPage.addClass('right');
                $nextPage.addClass('left');
                $nextAnimator.addClass('right');
                $currentAnimator.addClass('left');
            } else {
                $currentPage.addClass('left');
                $nextPage.addClass('right');
                $nextAnimator.addClass('left');
                $currentAnimator.addClass('right');
            }

            // clones animate
            privateMethods.setupTransition($el[0], $animatorWrap[0], $currentAnimator[0], $nextAnimator[0], leftToRight, settings);

            var deferred = $.Deferred();
            $.support.css.transition.registerTransitionEndListener($animatorWrap[0], deferred).done(function(){
                // cleanup
                $afterShadow.remove();
                $beforeShadow.remove();
                $animatorWrap.remove();
                $nextPage.removeClass('left right');
                $currentPage.removeClass('left right');
                $el[0].style[$.support.css.transform.perspectiveCssName] = '';
                $el[0].style[$.support.css.transform.styleCssName] = '';
            });

            // Start transition.
            setTimeout(function(){
                var rotation = leftToRight ? 'rotateY(180deg)' : 'rotateY(-180deg)';
                $animatorWrap[0].style[$.support.css.transform.cssName] = rotation;
                if (settings.shadow) {                
                    $beforeShadow[0].style[$.support.css.transition.cssName] = privateMethods.getTransitionStyle('opacity', settings.turnDuration / 2, settings.transitionTiming);
                    $afterShadow[0].style[$.support.css.transition.cssName] = privateMethods.getTransitionStyle('opacity', settings.turnDuration / 2, settings.transitionTiming, settings.turnDuration / 2);
                    $beforeShadow.css({opacity: 0});
                    $afterShadow.css({opacity: settings.shadowOpacity});
                }
            }, 20);
            return deferred.promise();
        },
        slideTransition: function($currentPage, $nextPage, leftToRight, settings){
            $nextPage.addClass('active');
            $currentPage.css({left: '0%'});
            if (leftToRight){
                $nextPage.css({left: '-100%'});
            }else{
                $nextPage.css({left: '100%'});
            }
            if ($.support.css.transition){
                var transitionStyle = privateMethods.getTransitionStyle('left', settings.slideDuration, settings.transitionTiming);
                $nextPage[0].style[$.support.css.transition.cssName] = transitionStyle;
                $currentPage[0].style[$.support.css.transition.cssName] = transitionStyle;
                setTimeout(function(){
                    $nextPage.css({left: '0%'});
                    $currentPage.css({left: (leftToRight ? '100%': '-100%')});
                }, 20);
                return $.support.css.transition.registerTransitionEndListener($nextPage[0]);
            }else{
                $currentPage.animate({left: (leftToRight ? '100%': '-100%')}, settings.slideDuration, settings.transitionTiming);
                return $nextPage.animate({left: '0%'}, settings.slideDuration, settings.transitionTiming).promise();
            }
        },
        fadeTransition: function($currentPage, $nextPage, settings){
            $currentPage.css({opacity: 1, 'z-index': 11}).show();
            $nextPage.css({opacity: 1, 'z-index': 10}).show();
            var promise = $currentPage.fadeOut(settings.fadeDuration).promise();
            promise.done(function(){
                $currentPage.css({'z-index': ''});
                $nextPage.css({'z-index': ''});
            });
            return promise;
        },
        getTransitionStyle: function(property, duration, timing, delay){
            var style = property + ' ' + duration + 'ms ' + timing;
            if (delay){
                style += ' ' + delay + 'ms';
            }
            return style;
        },
        setupTransition: function(el, animatorWrap, currentPane, nextPane, leftToRight, settings){
            el.style[$.support.css.transform.perspectiveCssName] = settings.perspective;
            el.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            animatorWrap.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            animatorWrap.style[$.support.css.transform.perspectiveCssName] = settings.perspective;
            animatorWrap.style[$.support.css.transition.cssName] = privateMethods.getTransitionStyle($.support.css.transform.cssHyphenName, settings.turnDuration, settings.transitionTiming);
            currentPane.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            currentPane.style[$.support.css.transform.cssName] = 'rotateY(0deg)';
            currentPane.style[$.support.css.transform.backfaceVisibilityCssName] = 'hidden';
            nextPane.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            if (leftToRight){
                currentPane.style[$.support.css.transform.originCssName] = 'right center';
                nextPane.style[$.support.css.transform.originCssName] = 'left center';
                nextPane.style[$.support.css.transform.cssName] = 'rotateY(-180deg) translateZ(1px)';
            }else{
                currentPane.style[$.support.css.transform.originCssName] = 'left center';
                nextPane.style[$.support.css.transform.originCssName] = 'right center';
                nextPane.style[$.support.css.transform.cssName] = 'rotateY(180deg) translateZ(1px)';
            }
        }
    };

    $.fn.uiPageTurn = function(method){
        if (methods[method]){
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }else if (typeof method === 'object' || !method){
            return methods.init.apply(this, arguments);
        }else{
            $.error('Method ' +  method + ' does not exist on jQuery.uiPageTurn' );
        }
    };
})(jQuery);
define("uiPageTurn", function(){});

(function($) {
    
    var dataName = 'uiPageTurn';
    var defaults = {
        useTransforms: !!$.support.css.transform,
        transitionTiming: 'linear',
        flipDuration: 300,
        flipFrontSelector: '.ui-flip-panel',
        flipBackSelector: '.ui-flip-panel',
        activePanelClass: 'active',
        perspective: '900px',
        fadeDuration: 200,

        onFlip: function($activePanel) {
        }
    };

    var methods = {
        init: function(options) {
            return this.each(function() {
                var $this = $(this);
                var settings = $.extend({}, defaults, options);
                $this.data(dataName, {
                    busy: false,
                    settings: settings
                });
            });
        },
        option: function(key, value) {
            var data = this.data(dataName);
            if (data && key) {
                if (value) {
                    if (typeof(value) === 'function' || key !== 'onFlip') {
                        data[key] = value;
                    }
                } else {
                    return data[key];
                }
            }
        },
        flipForward: function(immediate) {
            var data = this.data(dataName),
                settings = data.settings,
                panels = this.find(settings.flipFrontSelector);
            return privateMethods.transition(this, panels.filter('.active'), panels.filter(':not(.active)'), true, settings, data, immediate);
        },
        flipBackward: function(immediate) {
            var data = this.data(dataName),
                settings = data.settings,
                panels = this.find(settings.flipFrontSelector);
            return privateMethods.transition(this, panels.filter('.active'), panels.filter(':not(.active)'), false, settings, data, immediate);
        }
    };

    var privateMethods = {
        transition: function($wrapper, $front, $back, forward, settings, data, immediate) {
            var promise;

            if (data.busy) {
                return $.Deferred().reject();
            }
            if (immediate) {
                settings.onFlip($back);
                $back.addClass('active');
                $front.removeClass('active');
                return $.Deferred().resolve();
            }
            data.busy = true;

            $back.addClass('active');
            if (settings.useTransforms) {
                promise = privateMethods.flipTransform($wrapper[0], $front[0], $back[0], forward, settings);
            } else {
                promise = privateMethods.fadeTransition($front, $back, settings);
            }
            promise.done(function() {
                settings.onFlip($back);
                data.busy = false;
                $front.removeClass('active');
            });
            return promise;
        },
        flipTransform: function(wrapper, front, back, forward, settings) {
            privateMethods.setupTransition(wrapper, front, back, forward, settings);

            var deferred = $.Deferred();
            $.support.css.transition.registerTransitionEndListener(wrapper, deferred).done(function() {
                // cleanup
                front.style[$.support.css.transform.backfaceVisibilityCssName] = '';
                front.style[$.support.css.transform.styleCssName] = '';
                front.style[$.support.css.transition.cssName] = '';
                front.style[$.support.css.transform.cssName] = '';
                back.style[$.support.css.transform.backfaceVisibilityCssName] = '';
                back.style[$.support.css.transform.styleCssName] = '';
                back.style[$.support.css.transition.cssName] = '';
                back.style[$.support.css.transform.cssName] = '';
                wrapper.style[$.support.css.transform.perspectiveCssName] = '';
                wrapper.style[$.support.css.transform.styleCssName] = '';
            });

            // Start transition.
            setTimeout(function() {
                var rotation = 'rotateX(' + (forward ? '' : '-') + '180deg)';
                front.style[$.support.css.transform.cssName] = rotation;
                back.style[$.support.css.transition.cssName] = privateMethods.getTransitionStyle($.support.css.transform.cssHyphenName, settings.flipDuration, settings.transitionTiming);
                back.style[$.support.css.transform.cssName] = 'rotateX(0deg)';
            }, 20);
            return deferred.promise();
        },
        fadeTransition: function($front, $back, settings) {
            $front.css({opacity: 1, 'z-index': 11}).show();
            $back.css({opacity: 1, 'z-index': 10}).show();
            var promise = $front.fadeOut(settings.fadeDuration).promise();
            promise.done(function() {
                $front.css({'z-index': ''});
                $back.css({'z-index': ''});
            });
            return promise;
        },
        getTransitionStyle: function(property, duration, timing, delay) {
            var style = property + ' ' + duration + 'ms ' + timing;
            if (delay) {
                style += ' ' + delay + 'ms';
            }
            return style;
        },
        setupTransition: function(wrapper, front, back, forward, settings) {
            var backRotation = 'rotateX(' + (forward ? '-' : '') + '180deg)';
            wrapper.style[$.support.css.transform.perspectiveCssName] = settings.perspective;
            wrapper.style[$.support.css.transform.styleCssName] = 'preserve-3d';

            front.style[$.support.css.transform.backfaceVisibilityCssName] = 'hidden';
            front.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            front.style[$.support.css.transition.cssName] = privateMethods.getTransitionStyle($.support.css.transform.cssHyphenName, settings.flipDuration, settings.transitionTiming);
            front.style[$.support.css.transform.cssName] = 'rotateX(0deg)';

            back.style[$.support.css.transform.backfaceVisibilityCssName] = 'hidden';
            back.style[$.support.css.transform.styleCssName] = 'preserve-3d';
            back.style[$.support.css.transform.cssName] = backRotation;
        }
    };

    $.fn.uiFlip = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.uiPageTurn');
        }
    };
})(jQuery);
define("uiFlip", function(){});

/**
 * @fileoverview Hero module view.
 * @author Chad Shryock <cdshryock@gannett.com>
 */
define('views/modules/hero',['jquery',
    'underscore',
    'backbone',
    'baseview',
    'pubsub',
    'state',
    'views/modules/video',
    'views/modules/carousel',
    'sharedAdPosition',
    'views/modules/partner/leavebehind',
    'uiPageTurn',
    'uiFlip'
],
function(
    $,
    _,
    Backbone,
    BaseView,
    PubSub,
    StateManager,
    Video,
    Carousel,
    SharedAdPosition,
    LeaveBehind
    ) {
        /**
         * View class.
         */
        var HeroView = BaseView.extend({

            // Events.
            events: {
                'click .slide' : 'open',
                'click .hero-asset-open' : 'open',
                'click .carousel-thumbs > li' : 'openTile',
                'click .hero-turn-trigger, .hero-popular .hero-page-trigger' : 'toggleFrontBack',
                'click .partner-close': 'closeAdClick'
            },

            destroy: function(removeEl) {
                if (this.adShowing) {
                    this.closeAd(true);
                }
                var $belowHeroPopular = this.belowHeroModule.find('.below-hero-popular');
                if($belowHeroPopular.length){
                    $belowHeroPopular.empty();
                }
                BaseView.prototype.destroy.call(this, removeEl);
            },

            initialize: function(options){
                // remember that the durations are the duration for each stage of the animation
                // (0 -> 90, -90 -> 0)
                // so a complete animation is 2x duration
                options = $.extend(true, {animate: {duration: 200},
                        popularCount: 8,
                        shadow: {
                            opacity: '.4',
                            duration: 200,
                            delay: 0
                        }
                    }, options);
                BaseView.prototype.initialize.call(this, options);

                _.bindAll(this, '_finishAnimation', 'onVideoShow', 'onVideoHide', 'onAdReady', 'showHeroAd', 'belowHeroAdReady');

                this.visibleFace = 'front';

                this.mostPopularLoaded = false;
                this.isPageTurn = this.$el.hasClass('hero-page-turn');
                if (this.isPageTurn){
                    this.$el.uiPageTurn({
                        perspective: '1400px'
                    });
                } else {
                    this.$el.uiFlip({
                        perspective: '1400px'
                    });
                }
                this.adShowing = false;

            
                // Initialize the hero module's carousel when needed.
                if (this.$el.hasClass('carousel')) {
                    this.subviews.heroCarousel = new Carousel({
                        el : this.$el,
                        ads: false,
                        hoverTransition: 200,
                        thumbsSelector: '.carousel-thumbs',
                        rotate: true,
                        autostart: true
                    });
                }
                // Initialize each video as its own video instance.
                this.subviews.video = [];
                this.$('.video').each(_.bind(function(idx, el) {
                     var video = new Video({
                        // Use .video parent() because hero markup is different.
                        el: $(el).parent().get(0),
                        onVideoShow: this.onVideoShow,
                        onVideoHide: this.onVideoHide
                    });
                    this.subviews.video.push(video);
                }, this));

                this.$('.partner-heroflip-ad').each(_.bind(function(idx, el){
                    if (idx > 0){
                        console.error('why are there multiple ad placements for this hero?');
                        return;
                    }
                    this.subviews.ad = new SharedAdPosition({
                        el: el,
                        adSizes: ['heroflip'],
                        adPlacement: 'high_impact',
                        adType: 'heroflip',
                        onAdReady: this.onAdReady
                    });
                }, this));
            },
            render: function(currentCardInfo) {

                var hasMostPopular = this.$('.popular').length;
                if (hasMostPopular || currentCardInfo.belowHeroAd) {
                    if (this.$el.height() < 520) {
                        this.options.popularCount = 6;
                    }
                    var popularUrl = '/services/most-popular/hero/' + this.options.section + '/' + this.options.popularCount + '/';
                     this.mostPopularPromise = StateManager.fetchHtml(popularUrl);
                    if (hasMostPopular){
                        this.mostPopularPromise.done(_.bind(function(htmlFrag){
                            this.$('.popular .ui-placer').html(htmlFrag);
                            this.$('.hero-turn-trigger').fadeIn(500);
                            this.mostPopularLoaded = true;
                        }, this));
            
                    }
                    if (currentCardInfo.belowHeroAd) {
                        this.belowHeroModule = this.$el.next('.below-hero-ad-module');
                        if (this.belowHeroModule.length) {
                            this.subviews.belowHeroAd = new SharedAdPosition({
                                el: this.belowHeroModule.find('.below-hero-ad'),
                                adSizes: ['mediumrectangle'],
                                adPlacement: 'high_impact',
                                adType: 'below_hero',
                                defaultPosition: true,
                                onAdReady: this.belowHeroAdReady
                            });
                        }
                    }
                }
            },
            belowHeroAdReady: function() {
                this.mostPopularPromise.done(_.bind(function(htmlFrag) {
                    var articles = htmlFrag.find('.hero-popular-large-item:lt(2)'),
                        articleData = [],
                        template = _.template(this.belowHeroTemplate);
                        $(articles).each(function(index){
                            var obj = {
                                image: $(this).find('img').data('1x1'),
                                link:  $(this).find('a').attr('href'),
                                text:  $(this).find('h2').html()
                            };
                            articleData.push(obj);
                        });
                        var html = template({ articles: articleData });
                    this.belowHeroModule.find('.below-hero-popular').append(html);
                    this.subviews.belowHeroAd.playAd();
                }, this));
            },
            belowHeroTemplate: "<h3 class='below-hero-header-title title'>Stories You Shouldn't Miss</h3><ul class=\"stage clearfix below-hero-content-ul\" >" 
                                    +"<% _.each( articles, function(article,i) { %>"
                                        +"<li class=\"below-hero-content-li\"><a class='below-hero-content-a below-content-<%=i%>'href='<%=article.link%>'><img  class='featured-content-img' width='120' height='120' src='<%=article.image %>'/> "
                                        +"<h3 class=\"headline below-hero-h3\"><%= article.text %></h3></a></li>"
                                    +" <% }) %>"
                                +"</ul>",
            onAdReady: function(adInfo) {
                if (adInfo.leaveBehindImage && adInfo.leaveBehindText) {
                    this.createAdLeaveBehind(this.subviews.ad, adInfo.leaveBehindImage, adInfo.leaveBehindText);
                } else {
                    // no leave behind, no close button
                    this.$('.partner-close').hide();
                    this.showHeroAd();
                }
            },
            createAdLeaveBehind: function(ad, imageUrl, altText) {
                this.subviews.adLeaveBehind = new LeaveBehind({
                    el: StateManager.getActiveApp().$('.partner-leavebehind'),
                    onShowAd: this.showHeroAd,
                    imageUrl: imageUrl,
                    altText: altText,
                    isCompact: StateManager.getActiveApp().isCurrentCardBumped()
                });
                this.subviews.adLeaveBehind.render(ad);
            },
            showHeroAd: function() {
                this.adShowing = true;
                PubSub.trigger('sidebar:button:hide');
                this.subviews.ad.show();
                return this.triggerAnimation(_.bind(function(){
                    var promise;
                    if (this.isPageTurn) {
                        promise = this.$el.uiPageTurn('goToPage', 2);
                    } else {
                        promise = this.$el.uiFlip('flipForward');
                    }
                    promise.done(_.bind(function(){
                        this.subviews.ad.playAd();
                    }, this));
                    return promise;
                }, this));
            },

            /**
             * close ad click event
             * @param {Event} e click event
             */
            closeAdClick: function(e){
                e.preventDefault();
                this.closeAd();
            },
            closeAd: function(immediate){
                this.adShowing = false;
                if ($('.close-sidebar').css('display') === 'none') {
                    PubSub.trigger('sidebar:button:show');
                }
                this.subviews.ad.stopAd();
                this.triggerAnimation(_.bind(function(){
                    var promise;
                    if (this.isPageTurn){
                        if (this.visibleFace === 'front') {
                            promise = this.$el.uiPageTurn('goToPage', 0, immediate);
                        } else {
                            promise = this.$el.uiPageTurn('goToPage', 1, immediate);
                        }
                    } else {
                        promise = this.$el.uiFlip('flipBackward', immediate);
                    }
                    return promise;
                }, this)).done(_.bind(function(){
                    if (this.subviews.adLeaveBehind){
                        this.subviews.adLeaveBehind.show();
                    }
                }, this));
                return false;
            },

            triggerAnimation: function(action){
                this._setupAnimation();
                return this.registerAnimation(action()).done(this._finishAnimation);
            },

            onVideoShow: function(){
                this.$('.hero-turn-trigger').hide();
            },

            onVideoHide: function(){
                this.$('.hero-turn-trigger').show();
            },

            /**
             * Open anchor.
             * @param {Event} event View click event.
             */
            open: function(event) {
                var $currentTarget = $(event.currentTarget);
                if ($currentTarget.find('.text.video').length === 0 && !$(event.target).is('a')) {
                    $currentTarget.find('.story > h1 > a').trigger('click');
                } else if ($currentTarget.find('.text.video').length > 0 && !$(event.target).hasClass('videoStillPlay')) {
                    $(event.target).find('.videoStillPlay').click();
                }
            },

            openTile: function(event) {
                var index = $(event.currentTarget).index();
                this.$('.slide:eq(' + index + ') .story > h1 > a').click();
            },

            _setupAnimation: function(){
                // because of the size-well's all having z-index of 1 for the live feed, we need to
                // temporarily move it to 2, so it's above the size-well beneath us
                this.$el.closest('.size-well').css({'z-index': 6});
            },
            _finishAnimation: function(promise){
                // reset the size-well z-index to avoid headaches later
                this.$el.closest('.size-well').css({'z-index': ''});
            },

            /**
             * Toggle between the front and back views.
             * @param {Event} event View click event.
             */
            toggleFrontBack: function(event) {
                var promise, $trigger = $(event.currentTarget),
                    face = $trigger.attr('data-side');
                if (!this.mostPopularLoaded){
                    return false;
                }
                this.triggerAnimation(_.bind(function(){
                    if (face === 'front'){
                        promise = this.$el.uiPageTurn('nextPage');
                        this.visibleFace = 'back';
                        PubSub.trigger('uotrack', 'mostpopularopen');
                    }else{
                        promise = this.$el.uiPageTurn('prevPage');
                        this.visibleFace = 'front';
                        PubSub.trigger('uotrack', 'mostpopularclose');
                    }
                    return promise;
                }, this));
                return false;
            }
        });

        /**
         * Return view class.
         */
        return HeroView;
    }
);

/**
 * @fileoverview Global preloaders
 * @author mdkennedy@gannett.com (Mark Kennedy)
 */
define('views/modules/loader',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App
) {

    /**
     * View class.
     */
    var Loader = Backbone.View.extend({

        /**
         * Initialize the view.
         */
        initialize: function(options) {
            
            this.options = $.extend({
                msg: ''
            }, options || {});

            this.win = App.get('win');
            this.body = App.get('body');
            this.el = $(this.options.el);
            this.msg = this.options.msg;

            this.render();
        },

        /**
         * Create markup for loader.
         */
        render: function() {

            var $circDiv = $('<div>').addClass('loading-icon'),
                i;

            this.$loader = $('<div>').addClass('ui-loader');
            this.$target = this.$el;
            this.$target.append(this.$loader.append($circDiv).append($('<span>').html(this.msg)));
            this.$el = this.$loader;

        },

        destroy: function(removeEl){
            this.hide();
            if (removeEl){
                this.remove();
            }
        },

        /**
         * Display loader.
         */
        show: function() {
            this.$loader.addClass('active');
        },

        /**
         * Hide the loader.
         */
        hide: function() {
            this.$loader.removeClass('active');
        }

    });

    /**
     * Return view class.
     */
    return Loader;
});

/**
 * @fileoverview Gallery Carousel module view.
 * @author pkane, cwmanning
 */
define('views/modules/gallery-carousel',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'baseview',
    'app',
    'views/modules/carousel',
    'views/modules/loader',
    'state'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    BaseView,
    App,
    Carousel,
    Loader,
    StateManager
) {
    
        /**
         * View class.
         */
        var GalleryCarouselView = BaseView.extend({

            /*
             * Analytics must ignore a gallery "switch" which is not really a switch
             */
            empty: true, 

            /**
             * Events
             */
            events: {
                'click #CList-galleries li' : 'select'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                this.$galleries = this.$('.front-gallery');
                this.$navItems = this.$('.galleries li');

                _.bindAll(this, 'switchGallery');

                this.loader = new Loader({
                    el: this.$galleries.parent()
                });

                // call base class initialize
                BaseView.prototype.initialize.call(this, {});

                if (this.$galleries.find(".slide.active").length) {
                    var $gallery = this.$(".front-gallery.selected");
                    this.subviews['gallery' + $gallery.index()] = new Carousel({
                        ads: true,
                        linkPath: this.$navItems.filter('.selected').find('a').attr('href'),
                        el: $gallery.find('.mod.galleries'),
                        fullScreen: true
                    });
                    this.empty= false;
                } else {
                    var href = this.$navItems.first().find("a").attr("href");
                    if (typeof href !== 'undefined' && href.length > 1) {
                        this.fetchData(href, 0, this.switchGallery);
                    }
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.loader.destroy(removeEl);

                // call base class destroy
                BaseView.prototype.destroy.call(this, removeEl);
            },

            /**
             * Fetch data from server via AJAX. Takes a path to fetch and a
             * callback to parse the data and initialize views.
             * @param {String} path The path to the ajax endpoint.
             * @param {Number} index The Gallery list item position.
             * @param {Function} callback Function to call when data is returned
             *      from server.
             */
            fetchData: function(path, index, callback) {
                var _this = this;
                // state manager failures return immediately without waiting for the promises to finish
                // so we need to track whether we're still loading after the animation is running
                var loading = true;

                var $gallery = this.$(".front-gallery.selected");
                if ($gallery.length){
                    $gallery.css({'opacity': 1});
                    this.animate($gallery, 'opacity', 0, 200).done(function(){
                        if (loading){
                            _this.loading(true);
                        }
                    });
                }
                StateManager.fetchHtml(path, {data: {type: 'front'}})
                    .done(function(html){
                        callback(html, index,path);
                    }).always(function(){
                        loading = false;
                        _this.loading(false);
                    });
            },

            /**
             * Toggle loading presentation
             * @param {boolean} showLoading Whether or not to display loading.
             */
            loading: function(showLoading) {
                if (showLoading) {
                    this.loader.show();
                } else {
                    this.loader.hide();
                }
            },

            /**
             * Toggle selected class and load gallery data.
             * @param {Event} event View click event.
             */
            select: function(event) { 
                var $item = $(event.currentTarget);
                var index = $item.index();
                var $gallery = this.$galleries.eq(index);
                var targetLink = $item.find('a');
                var path = targetLink.attr('href');

                // Heattracking
                App.setTrack(targetLink);

                if (path.indexOf('http') !== 0) {
                    if ($gallery.find('.galleries').length > 0) {
                        this.switchGallery(null, index, path);
                    } else {
                        this.fetchData(path, index, this.switchGallery);
                    }

                    if (event) {
                        event.preventDefault();
                    }
                }

                // Highlight clicked navigation item.
                this.$navItems.removeClass('selected');
                $item.addClass('selected');
            },

            /**
             * Switch to selected gallery.
             * @param {String} html Returned from fetchData.
             * @param {Number} index The Gallery list item position.
             * @param {String} path url for the gallery associated with the html.
             */
            switchGallery: function(html, index, path) {
                var $gallery = this.$galleries.eq(index);

                // Show chosen gallery.
                this.$galleries.removeClass('selected');
                $gallery.addClass('selected');

                if (html) {
                    $gallery.html(html);
                }
                if (!this.subviews['gallery' + index]) {
                    var carousel = this.subviews['gallery' + index] = new Carousel({
                        ads: true,
                        el: $gallery.find('.mod.galleries'),
                        fullScreen: true,
                        linkPath: path
                    });
                    if (!this.empty) {
                        this.trackGalleryChange(carousel);
                        this.empty = false;
                    }
                } else {
                    this.trackGalleryChange(this.subviews['gallery' + index]);
                }
                $gallery.css({opacity: 0});
                this.animate($gallery, 'opacity', 1, 200);
            },

            // carousel is not issuing a slide:change event for our first slide
            // so... ask it to do so
            trackGalleryChange: function(carousel) {
                carousel._trackSlideChange();
            }
        });

        /**
         * Return view class.
         */
        return GalleryCarouselView;
    }
);

/**
 * @fileoverview Headlines module view.
 * @author Chad Shryock <cdshryock@gannett.com>
 */
define('views/modules/headline',[
    'jquery',
    'underscore',
    'backbone',
    'state',
    'pubsub',
    'app',
    'baseview',
    'views/modules/form/button-toggle'
],
function(
    $,
    _,
    Backbone,
    StateManager,
    PubSub,
    App,
    BaseView,
    ButtonToggle
) {
    
    /**
     * View class.
     */
    var HeadlineView = BaseView.extend({

        // Events.
        events: {
            'click .button-add-content': 'showMore'
        },

        /**
         * Initialize view.
         * @param {Object} options View options passed in during init.
         */
        initialize: function(options) {
            this.itemsPerPage = this.$el.data('itemsPerPage');
            this.$button = this.$('.button-add-content');
            this.section = options.section + 'front';
            BaseView.prototype.initialize.call(this, options);
            _.bindAll(this, 'transitionMore', 'toggleGridListView');

            // setup view toggler
            var toggler = this.$('.headline-toggler');
            if (toggler.length) {
                this.subviews.gridListViewToggler = new ButtonToggle({
                    el: toggler,
                    onSelect: this.toggleGridListView
                });
            }
        },

        getMoreHeadlines: function(nextPageNum, callback) {
            StateManager.fetchHtml(window.location.pathname + nextPageNum + '/').done(
                _.bind(function(htmlFrag){
                    var $page = htmlFrag.find('.page').removeClass('active').addClass('inactive');
                    var $button = htmlFrag.find('.button-add-content');
                    this.$('.collection').append($page);
                    if ($button.length > 0) {
                        this.$('.show-more').html($button);
                    } else {
                        this.$button.addClass('inactive');
                    }
                    callback($page);
                }, this)
            ).fail(_.bind(function(){
                var origText = this.$button.attr('data-default');
                this.$button.removeClass('loading').addClass('inactive').text(origText);
            }, this));
        },

        /**
         * Shows the next block of headlines.
         * @param {Event} event View click event.
         */
        showMore: function(event) {
            if ($(event.target).hasClass('inactive')) return false;
            this.$button = $('.button-add-content',this.el);
            this.$button.addClass('loading').text(this.$button.attr('data-loading'));
            var $nextPage;
            if (this.$el.hasClass('stag')) {
                var nextPageNum = parseInt($(event.target).data('next'), 10);
                this.getMoreHeadlines(nextPageNum, this.transitionMore);
            } else {
                // On a typical front - headlines already in DOM.
                $nextPage = this.$('.page.active:last').next();
                var ditemnum = $nextPage.attr("data-itemnum");
                var ditemperpage = $nextPage.attr("data-items-per-page");
                var count = Math.round(ditemnum/ditemperpage);
                var $collection = $('.headlines .collection');
                var dataSrc;
                if($collection.hasClass('listview')){
                    dataSrc = "data-list-src";
                } else {
                    dataSrc = "data-grid-src";
                }
                
                App.lazyLoadImage($nextPage.find('img'), dataSrc, true);

                PubSub.trigger('uotrack', this.section+'morestories'+count);
                this.transitionMore($nextPage);
            }
            event.preventDefault();
        },

        /**
         * Toggle between list and grid modes
         * @param {Jquery} clickedToggleItem Clicked toggle item
         */
        toggleGridListView: function(clickedToggleItem) {
            var $collection = this.$('.collection');
            var viewState = clickedToggleItem.hasClass('grid-big') ? 'grid-big' : 'list-big';
            if (viewState === 'list-big') {
                $collection.addClass('listview');
                PubSub.trigger('uotrack', 'listview');
                App.lazyLoadImage(this.$('img'), 'data-list-src', true);
            } else {
                $collection.removeClass('listview');
                PubSub.trigger('uotrack', 'gridview');
                App.lazyLoadImage(this.$('img'), 'data-grid-src', true);
            }
        },

        transitionMore: function($nextPage) {
            var $collection = $('.headlines .collection');
            var dataSrc;
            if (Modernizr.csstransitions) {
                $nextPage.removeClass('inactive').addClass('active');
            } else {
                $nextPage.animate({
                    'max-height': '5000px'
                }, 200, function() {
                    $(this).removeClass('inactive').addClass('active').css('max-height', '');
                });
            }
            if (this.$('.page.inactive').length <= 0) {
                // no more items to show, inactivate the show more button
                this.$button.addClass('inactive');
            }
            if($collection.hasClass('listview')){
                    dataSrc = "data-list-src";
            } else {
                    dataSrc = "data-grid-src";
            }
            
            App.lazyLoadImage($nextPage.find('img'), dataSrc, true);

            this.$button.removeClass('loading').text(this.$button.attr('data-default'));
            PubSub.trigger('showmore:headlines');
        }

    });

    /**
     * Return view class.
     */
    return HeadlineView;
});
/**
 * @fileoverview Homepage view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 */
define('views/pages/base-page',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'baseview',
    'state',
    'views/modules/live-feed-view',
    'views/modules/footer',
    'views/modules/hero',
    'views/modules/carousel',
    'views/modules/gallery-carousel',
    'views/modules/headline'
],
function(
    $,
    _,
    Backbone,
    App,
    PubSub,
    BaseView,
    StateManager,
    LiveFeedView,
    Footer,
    Hero,
    Carousel,
    GalleryCarousel,
    Headline
)
    {

        /**
         * View class.
         */
        var BasePageView = BaseView.extend({
            /**
             * Initialize view.
             */
            initialize: function(options) {
                if (options.path.substr(-1) === '/') {
                    options.path = options.path.substr(0, options.path.length - 1);
                }
                options = $.extend(true, {
                    liveFeedColor: 'light'
                }, options);
                this.expandedviews = {};

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },


            /**
             * Load data.
             */
            render: function(currentCardInfo) {
                // Initialize the hero module.
                this.subviews.hero = new Hero({
                    el : this.$('.hero:first'),
                    section: this.options.section
                });
                // Send current card info to hero
                this.subviews.hero.render(currentCardInfo);

                // Initialize the gallery list.
                this.subviews.galleryList = new GalleryCarousel({
                    el : this.$('.front-galleries')
                });

                // Initialize the headline.
                this.subviews.headline = new Headline({
                    el : this.$('.mod.headlines'),
                    section : this.options.section //for tracking
                });

                // Initialize footer.
                this.subviews.footer = new Footer();
            },

            renderExpanded: function(currentCardInfo){
                if (this.$('.mod.live-feed').length) {
                    // Initialize the live feed.
                    this.subviews.livefeed = this.expandedviews.livefeed = new LiveFeedView({
                        el : this.$('.mod.live-feed'),
                        ads: currentCardInfo.sidebarAds,
                        section: this.options.path,
                        color: this.options.liveFeedColor
                    });
                    this.expandedviews.livefeed.render(currentCardInfo);
                }
            },

            destroy: function(removeEl){
                this.destroyExpanded(removeEl);

                // call base class destroy
                BaseView.prototype.destroy.apply(this, arguments);
            },

            destroyExpanded: function(removeEl){
                this._callCollection(this.expandedviews, 'destroy', [removeEl]);
                this.expandedviews = {};
            },

            onCardWidthChange : function(newCardInfo) {
                if (!newCardInfo.sidebarAds){
                    this.triggerEvent('onHideSidebarAd');
                }
                this.triggerEvent('onCardWidthChange', newCardInfo);
            }

        });


        /**
         * Return view class.
         */
        return BasePageView;
    }
);

/**
 * @fileoverview Twitter view module.
 * @author jheiner@usatoday.com (John Heiner)
 */
define('views/modules/twitter',[
    'jquery',
    'underscore',
    'backbone',
    'state',
    'pubsub',
    'baseview',
    'views/modules/scroller/sidebar-scroll'
],
function(
    $,
    _,
    Backbone,
    StateManager,
    PubSub,
    BaseView,
    SidebarScroll
) {

    
        /**
         * View class.
         */
        var TwitterView = BaseView.extend({

            /**
             * Initialize view.
             * @param {Object} options
             */
            initialize: function(options) {
                this.options = $.extend({
                    num_tweets: 6,
                    columns: 1,
                    default_account: null,
                    sidebar: false
                }, options || {});

                // clear the el top in case an ad used to be showing after we close an overlay
                this.onHideSidebarAd();

                this.tweetTemplate = this.$('#tweet-list-template');

                if (!this.tweetTemplate.length) {
                    return;
                }

                _.bindAll(this, 'createTweetsHTML');
                this.twitter_el = this.$('.tweet-list');

                // Check if the JSON user attr is there otherwise use current section feed.
                var userID = this.twitter_el.attr('data-user-id');
                var default_account = this.twitter_el.attr('data-section-id') || this.options.default_account;
                // Logic and fallbacks for twitter user, will try json user, than section, than USAToday users.
                if (!userID) {
                    userID = default_account || 'USAToday';
                }
                this.loadTweets(userID, this.options.num_tweets, this.createTweetsHTML);

                // Call base class initialize.
                BaseView.prototype.initialize.call(this, this.options);
            },

            destroy: function(removeEl) {
                if (removeEl) {
                    this.twitter_el.empty();
                }
                BaseView.prototype.destroy.call(this, false);
            },

            /**
             * Update size when a sidebar ad shows up.
             */
            onShowSidebarAd: function(ad) {
                this.$el.css('height', this.$el.outerHeight() - ad.getHeight());
                if (this.subviews && this.subviews.scrollbar) {
                    this.subviews.scrollbar.refresh();
                }
            },

            /**
             * Update size when a sidebar ad is hidden.
             */
            onHideSidebarAd: function() {
                this.$el.css('height', '');
                if (this.subviews && this.subviews.scrollbar) {
                    this.subviews.scrollbar.refresh();
                }
            },

            loadTweets: function(user, tweetCount, callback) {
                var _this = this;
                StateManager.fetchData('http://api.twitter.com/1/statuses/user_timeline.json', {
                    dataType: 'jsonp',
                    data: {
                        screen_name: user,
                        include_rts: true,
                        count: tweetCount,
                        include_entities: false
                    }
                }).done(function(data) {

                    // Append tweets into page.
                    var clean = [],
                        i,
                        data_length = data.length;

                    for (i = 0; i < data_length; i++) {
                        data[i].text = _this.ify.clean(data[i].text);
                        data[i].created_at = _this.timeAgo(data[i].created_at);
                        clean.push(data[i]);
                    }

                    callback(clean);
                });
            },

            /**
             * Calls the template file and fills it with the tweets
             */
            createTweetsHTML: function(tweets) {
                var compiled = _.template(this.tweetTemplate.html(), {data: tweets});
                this.twitter_el.html(compiled);
                this.twitter_el.find('li').slice(0, this.options.columns).addClass('no-border');

                // Add scrollbar if the module is on sidebar
                if (this.options.scroller) {
                    this.addScrollbar();
                }
            },

            /**
             * Add scrollbar.
             */
            addScrollbar: function() {
                this.subviews.scrollbar = new SidebarScroll({
                    el: this.$('.twitter-scroll-content'),
                    color: 'light',
                    lockPageScroll: true,
                    fadeout: true
                });
            },

            /**
             * relative time calculator FROM TWITTER
             * @param {String} dateString date string returned from Twitter API.
             */
            timeAgo: function(dateString) {
                var rightNow = new Date();
                var then = new Date(dateString);

                if ($.browser.msie) {
                    // IE can't parse these crazy Ruby dates
                    then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
                }

                var diff = rightNow - then;

                var second = 1000,
                    minute = second * 60,
                    hour = minute * 60,
                    day = hour * 24;

                if (isNaN(diff) || diff < 0) {
                    return ''; // return blank string if unknown
                }

                if (diff < second * 2) {

                    // Within 2 seconds
                    return 'right now';
                }

                if (diff < minute) {
                    return Math.floor(diff / second) + ' seconds ago';
                }

                if (diff < minute * 2) {
                    return 'about 1 minute ago';
                }

                if (diff < hour) {
                    return Math.floor(diff / minute) + ' minutes ago';
                }

                if (diff < hour * 2) {
                    return 'about 1 hour ago';
                }

                if (diff < day) {
                    return  Math.floor(diff / hour) + ' hours ago';
                }

                if (diff > day && diff < day * 2) {
                    return 'yesterday';
                }

                if (diff < day * 365) {
                    return Math.floor(diff / day) + ' days ago';
                }

                else {
                    return 'over a year ago';
                }
            },

            /**
             * The Twitalinkahashifyer!
             * http://www.dustindiaz.com/basement/ify.html
             * Eg:
             * ify.clean('your tweet text');
             */
            ify: {
                link: function(tweet) {
                    return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
                        var http = m2.match(/w/) ? 'http://' : '';
                        return '<a target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
                    });
                },

                at: function(tweet) {
                    return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
                        return '<a target="_blank" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
                    });
                },

                list: function(tweet) {
                    return tweet.replace(/\B[@ï¼ ]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
                        return '<a target="_blank" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
                    });
                },

                hash: function(tweet) {
                    return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
                        return before + '<a target="_blank" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
                    });
                },

                clean: function(tweet) {
                    return this.hash(this.at(this.list(this.link(tweet))));
                }
            } // ify

        });

        /**
         * Return view class.
         */
        return TwitterView;
    }
);


/**
 * @fileoverview Generic pagination view.
 * @author Erik Luchauer <eluchauer@gannett.com>
 *
 *
 * The following template is associated with this view.  This is the expected html for this view.
 * 
 * {% include "partials/generic-paginator.html" with items=data.interactive.events %}
 *
 * The following JavaScript is required to integrate the functionality of this sub-view with its parent view.
 *
 * this.subviews.pagination = new GenericPaginatorView({
 *     el: this.$el.find('.paginator'),
 *     onGoTo: function(index) {}
 * });
 */
define('views/modules/generic-paginator',['jquery', 'underscore', 'backbone', 'baseview', 'pubsub'],
    function($, _, Backbone, BaseView, PubSub) {

        /**
         * View class.
         */
        var GenericPaginatorView = BaseView.extend({

            // Events.
            events: {
                'click .paginator-indicator-target' : 'onPaginatorClick'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {

                this.$pageElements = this.$(".paginator-indicator-target");

                options = $.extend({
                    onGoTo:null // function(index), this is the callback for navigating to a paginated item
                }, options);

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },

            onPaginatorClick: function(event) {
                if (event) event.preventDefault();
                var pageNumber = $(event.currentTarget).index();
                
                this.goToPage(pageNumber);
            },

            // Public API

            /**
             * Updates the selected (active) bullet based on the click of its parent (.paginator-indicator-target) element.
             * Some parent views have ways of updating the pagination outside of clicking the actual page bullets.
             * This method allows those parent views to update the pagination when using their native page update methods.
             * @param {integer} pageNumber selected page number to switch to the active bullet
             */            
            goToPage: function(pageNumber) {
                if(this.$pageElements.length === 0){
                    return;
                }

                if(pageNumber < 0){
                    pageNumber = 0;
                } else if(pageNumber >= this.$pageElements.length) {
                    pageNumber = this.$pageElements.length - 1;
                }

                var $pageEl = this.$pageElements.eq(pageNumber);
                
                this.$('.paginator-indicator-bullet').removeClass('active');
                $pageEl.find('.paginator-indicator-bullet').addClass('active');
                if (this.options.onGoTo) {
                    this.options.onGoTo(pageNumber);
                }
            },

            goToNextPage: function(rotate) {
                // Cache the selectors.
                var $active = this.$('.paginator-indicator-bullet.active'),
                    currentIndex = $active.parent().index();

                // Triger the event on the next item in the list.
                // If on the last, and rotate is true, trigger the first.
                if(currentIndex < this.$pageElements.length - 1){
                    this.goToPage(currentIndex + 1);
                } else if (rotate) {
                    this.goToPage(0);
                }

            },

            goToPrevPage: function(rotate) {
                // Cache the selectors.
                var $active = this.$('.paginator-indicator-bullet.active'),
                    currentIndex = $active.parent().index();

                // Triger the event on the previous item in the list.
                // If on the first, and rotate is true, trigger the last.
                if(currentIndex > 0){
                    this.goToPage(currentIndex - 1);
                } else if (rotate) {
                    this.goToPage(this.$pageElements.length - 1);
                }

            }

        });

        /**
         * Return view class.
         */
        return GenericPaginatorView;
    }
);

/**
 * @fileoverview Featured Content module view.
 * @author Robert Huhn <rhuhn@usatoday.com>  and John Heiner <jheiner@usatoday.com>
 */
define('views/modules/featured-content',['jquery',
        'underscore',
        'backbone', 
        'baseview', 
        'pubsub',
        'views/modules/generic-paginator'
        ],
    function($, _, Backbone, BaseView, PubSub, GenericPaginatorView) {

        /**
         * View class.
         */
        var FeaturedContentView = BaseView.extend({

            // Events.
            events: {
                'mouseenter' : 'stoptimer',
                'mouseleave' : 'starttimer'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                _.bindAll(this, 'automate', 'goTo');

                options = $.extend({
                    itemWidth: 180,
                    itemsPerView: 4,
                    transition : {
                        interval : 15000
                    }
                }, options);
                this.subviews = {};

                this.moveMe = this.$('ul:first');

                this.subviews.paginator = new GenericPaginatorView({
                    el: this.$('.paginator'),
                    onGoTo: this.goTo
                });

                if (options.transition) {
                    this.interval = options.transition.interval || false;
                    this.timer = null;

                    if (this.interval) {this.starttimer();}
                }
                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },

            /*
             * Function to handle automated rotation of the carousel.
             */
            automate: function() {
                this.subviews.paginator.goToNextPage(true);
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.stoptimer();

                // call base class destroy
                BaseView.prototype.destroy.call(this, removeEl);
            },

            goTo: function(index) {
                var offsetBy = this.options.itemWidth * this.options.itemsPerView,
                    targetOffset = offsetBy*index,
                    cssObj = {'left': '-'+targetOffset+'px'},
                    start = (index * this.options.itemsPerView),
                    end = start + this.options.itemsPerView,
                    $img;

                this.animate(this.moveMe, 'left', '-'+targetOffset+'px', 450, 'ease-in-out');
                this.moveMe.find('li').each(function(index, li) {
                    // images are not guaranteed to exist in this set
                    $img = $(li).find('img');

                    if (index >= start && index < end && $img.attr("data-src")) {
                        $img.attr("src", $img.attr("data-src"));
                        $img.removeAttr('data-src');
                    }
                });
            },

            /*
             * Start the interval that automates slide switching.
             */
            starttimer: function() {
                if (this.interval && !this.timer){
                    this.timer = setInterval(this.automate, this.interval);
                }
            },

            /*
             * Stop the interval - primarily used when hovering the module.
             */
            stoptimer: function() {
                if (this.timer){
                    clearInterval(this.timer);
                    this.timer = null;
                }
            }

        });

        /**
         * Return view class.
         */
        return FeaturedContentView;
    }
);

/**
 * @fileoverview Blogs module view.
 * @author Chad Shryock <cdshryock@gannett.com>
 */
define('views/modules/blogs',['jquery', 'underscore', 'backbone', 'baseview', 'pubsub'],
    function($, _, Backbone, BaseView, PubSub) {


        /**
         * View class.
         */
        var BlogsView = BaseView.extend({

            // Events.
            events: {
                'click .scroller' : 'scroll'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {
                this.$moveMe = this.$('.stage ul');
                this.totalItems = $('li', this.$moveMe).length;
                this.$scrollerLeft = this.$('.scroller.left');
                this.$scrollerRight = this.$('.scroller.right');

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);
            },

            scroll: function(event) {
                if (event) event.preventDefault();

                // pressed scroller
                var $scroller = $(event.target);

                // ignore if disabled
                if ($scroller.hasClass('disabled')) {
                    return false;
                }

                // get the vars to do the math
                var isScrollRight = $scroller.hasClass('right');
                var currentItemOffset = this.$moveMe.data("item-offset");
                var byNoItems = 4;
                if (Modernizr.mq("screen and (min-width: 1250px)")) {
                    byNoItems = 6;
                } else if (Modernizr.mq("screen and (min-width: 1150px)")) {
                    byNoItems = 5;
                }

                // Item Offset Count
                if (isScrollRight) {
                    byNoItems = byNoItems * -1;
                }
                var newItemOffset = byNoItems + currentItemOffset;
                if (newItemOffset > 0) {
                    newItemOffset = 0;
                }

                // Item Offset Pixels
                var currentPixelOffset = (currentItemOffset * 183) - 1;
                var changePixelOffset = byNoItems * 183;
                var newPixelOffset = changePixelOffset + currentPixelOffset;
                newPixelOffset = (newItemOffset * 183) - 1;

                // Scroller Left enable/disable
                if (newItemOffset == 0) {
                    this.$scrollerLeft.addClass('disabled');
                } else {
                    this.$scrollerLeft.removeClass('disabled');
                }

                var totalNewDistance = Math.abs(newItemOffset) + Math.abs(byNoItems);
                // Scroller Right enable/disable
                if (totalNewDistance >= this.totalItems) {
                    this.$scrollerRight.addClass('disabled');

                    //only move enough to get the last ones in view
                    byNoItems += (totalNewDistance - this.totalItems);
                    newItemOffset = byNoItems + currentItemOffset;
                    changePixelOffset = byNoItems * 183;
                    newPixelOffset = changePixelOffset + currentPixelOffset;
                    newPixelOffset = (newItemOffset * 183) - 1;

                } else {
                    this.$scrollerRight.removeClass('disabled');
                }

                this.$moveMe.data("item-offset", newItemOffset);

                // Do the move.
                this.animate(this.$moveMe, 'left', newPixelOffset + 'px', 200, 'ease-in');
            }

        });

        /**
         * Return view class.
         */
        return BlogsView;
    }
);

/**
 * @fileoverview Featured (home page) module view.
 * @author Chris Manning <cwmanning@gannett.com>
 *
 * This module is a bit of a hack. But needed until we can manage 
 * these one-off navigation links in the CMS.
 */
define('views/modules/quick-links',[
    'jquery',
    'underscore',
    'backbone',
    'baseview'
],
function(
    $,
    _,
    Backbone,
    BaseView
) {

    /**
     * View class.
     */
    var QuickLinks = BaseView.extend({

        /**
         * Initialize view.
         * @param {string} sectionPath to pass in section name.
         * @param {object} jQuery object representing current card.
         */
        initialize: function(sectionPath, $card) {
            if ($('#CList-quick-links').length === 0 && $card.length === 1 && (sectionPath == 'home' || sectionPath == 'travel' || sectionPath == 'life' || sectionPath == 'news')) {
                var links = this.getLinks(sectionPath);
                var linkTemplate = $('#quick-links-template');

                if (links.length > 0 && linkTemplate.length === 1) {
                    var compiled = _.template(linkTemplate.html(), {data: links});
                    if (sectionPath == 'home') {
                        // If home, append specifically to the first suspender.
                        // The quick links need to come directly after markets,
                        // another dynamically generated element.
                        $card.find('.size-suspender:first').append(compiled);
                    } else {
                        // Search for suspenders to render quick links in the first available spot.
                        $card.find('.size-well').each(function() {
                            var $t = $(this);
                            var $sus = $t.children('.size-suspender');
                            if ($sus.length === 1) {
                                // Check for a child and its children (we appear to render empty divs by default).
                                if ($sus.children().length === 0 || $sus.children().eq(0).children().length === 0) {
                                    $sus.append(compiled);
                                    // Break out of loop.
                                    return false;
                                }
                            }
                        });
                    }
                }
            }
            BaseView.prototype.initialize.apply(this, arguments);
        },

        getLinks: function(sectionPath) {
            var links = [];
            if (sectionPath == 'home') {
                links = [
                    {
                        'url': '/sports/',
                        'text': 'Sports Scores'
                    },
                    {
                        'url': '/puzzles/crossword/',
                        'text': 'Crosswords'
                    },
                    {
                        'url': '/puzzles/sudoku/',
                        'text': 'Sudoku'
                    },
                    {
                        'url': 'http://puzzles.usatoday.com/',
                        'text': 'More Games',
                        'target': true
                    },
                    {
                        'url': '/interactives/tv-on-the-web/',
                        'text': 'TV on the Web'
                    },
                    {
                        'url': 'http://reg.e.usatoday.com/',
                        'text': 'Newsletters &amp; Alerts',
                        'target': true
                    }
                ];
            } else if (sectionPath == 'travel') {
                links = [
                    {
                        'url': '/blog/cruiselog/',
                        'text': 'Cruise Log'
                    },
                    {
                        'url': '/blog/todayinthesky/',
                        'text': 'Today in the Sky'
                    },
                    {
                        'url': '/blog/hotelcheckin/',
                        'text': 'Hotel Check-In'
                    },
                    {
                        'url': '/blog/dispatches/',
                        'text': 'Dispatches'
                    },
                    {
                        'url': '/topic/d8cb17b3-2f17-49d8-a552-712d93574ee3/travel-advice/',
                        'text': 'Travel Advice'
                    }
                ];
            } else if (sectionPath == 'life') {
                links = [
                    {
                        'url': 'http://books.usatoday.com/list/index',
                        'text': 'Best-Selling Books'
                    },
                    {
                        'url': 'http://tvlistings.zap2it.com/tvlistings/ZCGrid.do?aid=usatoday',
                        'text': 'TV Schedule',
                        'target': true
                    },
                    {
                        'url': '/interactives/tv-on-the-web/',
                        'text': 'TV on the Web'
                    }

                ];
            } else if (sectionPath == 'news') {
                links = [
                    {
                        'url': '/media/latest/news/usanow/',
                        'text': 'USA NOW'
                    },
                    {
                        'url': '/topic/d2591a44-dfd9-4d0d-af7a-cc0b3b92cbb0/health-and-wellness/',
                        'text': 'Health and Wellness'
                    },
                    {
                        'url': 'http://puzzles.usatoday.com',
                        'text': 'Crosswords',
                        'target': true
                    }
                ];
            }

            return links;
        }

    });

    /**
     * Return view class.
     */
    return QuickLinks;
});

/**
 * @fileoverview Lottery module view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define('views/modules/lottery',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'app',
    'views/modules/form/dropdown'
],
    function(
        $,
        _,
        BaseView,
        StateManager,
        App,
        Dropdown
        ) {
        
        /**
         * View class.
         */
        var LotteryView = BaseView.extend({

            /**
             * Initialize view.
             * @param {object} options to pass in module options
             */
            initialize: function(options) {

                options = $.extend({
                    refreshDelay: 6000, //ms
                    refresh: false
                },options);
                _.bindAll(this, 'updateLottery');
                BaseView.prototype.initialize.call(this,options);
                if (this.options.refresh) {
                    this.subviews.refreshInterval = StateManager.recurringFetchHtml('/lottery/front-module', null, this.options.refreshDelay, this.updateLottery);
                } else {
                    StateManager.fetchHtml('/lottery/front-module').done(this.updateLottery);
                }
            },

            updateLottery: function(html){
                this.$el.html(html);
                if (!this.subviews.selectDropdown){
                    this.setupDropdown();
                }
            },

            setupDropdown: function(){
                this.subviews.selectDropdown = new Dropdown({
                    el: this.$('.lottery-state-picker-dropdown')
                });
            }


        });

        /**
         * Return view class.
         */
        return LotteryView;
    }
);

/**
 * @fileoverview Kayak view module.
 * @author bbagley@gannett.com (Brendan Bagley)
 */
define('views/modules/travel/kayak-module',[
    'jquery',
    'underscore',
    'backbone',
    'state',
    'pubsub',
    'baseview'
],
function(
    $,
    _,
    Backbone,
    StateManager,
    PubSub,
    BaseView
) {
        /**
         * View class.
         */
        var KayakView = BaseView.extend({

            // View element.
            el: '.kayak-wrapper',

            // Events.
            events: {
                'click .kayak-btn-style': 'kayakWidgetBtnClick'
            },

            /**
             * Initialize view.
             * @param {Object} options
             */
            initialize: function(options) {
                var pageInfo = StateManager.getCurrentPageInfo();
                var ssts = pageInfo.ssts;
                var ss;
                if(ssts.indexOf('/')!=-1) {
                    ss=ssts.slice(7);
                }

                this.$active = this.$('.tab.active');
                this.$activeBtn = this.$('.kayak-btn-style.active');
                this.initTab = 'flights';

                if(!_.isUndefined(ss)) {
                    this.initTab = ss;
                }

                this.setTab(this.initTab);

                _.bindAll(this, 'kayakWidgetBtnClick', 'tabTransition');

                BaseView.prototype.initialize.call(this, this.options);
            },

            setTab: function(tabName) {
                var targetTabName = '.tab.'+tabName;
                var $targetTab = this.$(targetTabName);
                var btnName = '.kayak-btn-style.' + tabName;
                this.$activeBtn.removeClass('active');
                var $newActiveBtn = this.$(btnName);
                $newActiveBtn.addClass('active');
                this.$activeBtn = $newActiveBtn;

                if(!$targetTab.children().length) {
                    this.loadIframe(tabName);
                }
                this.tabTransition($targetTab, targetTabName);
            },

            loadIframe: function(type) {
                var params = {
                    cruises : 'n',
                    deals : 'n',
                    vacations : 'n',
                    hotels : 'n',
                    flights : 'y',
                    tab : 'flights'
                };
                if(type!='flights') {
                    params.tab = type;
                    params.flights = 'n';
                    params[type] = 'y';
                }
                var html = '<iframe src="http://usatoday.kayak.com/widget/300x250?cars=n&cruises=' + params.cruises + '&deals=' + params.deals + '&vacations=' + params.vacations + '&hotels=' + params.hotels + '&flights=' + params.flights + '&tab=' + params.tab + '&l1=!" width="300" height="250" frameborder="0" scrolling="no"></iframe>';
                var tabname = '.tab.' + params.tab;
                this.$(tabname).append(html);
            },

            kayakWidgetBtnClick: function(e) {
                var targetTabName;
                if(e.target.id.length) {
                    targetTabName = e.target.id;
                    this.setTab(targetTabName);
                }
            },

            tabTransition: function($goingTo, tabName) {
                if($goingTo[0] !== this.$active[0]) {
                    this.$active.hide().removeClass('active');
                    $goingTo.show().addClass('active');
                    this.$active = $goingTo;
                }
            }
        });

        /**
         * Return view class.
         */
        return KayakView;
    }
);


/**
 * @fileoverview Flightsearch view.
 * @author Brendan Bagley
 */

define('views/modules/travel/flight-search',[
    'jquery',
    'underscore',
    'pubsub',
    'state',
    'baseview',
    'form',
    'views/modules/form/autocomplete'
],
function(
    $,
    _,
    PubSub,
    StateManager,
    BaseView,
    FormView,
    AutoComplete
) {
    
    var FlightSearchView = BaseView.extend({

        events: {
            'submit form': 'flightSearchFormSubmit',
            'click .flight-tracker-search-btn' : 'flightSearchButtonClick',
            'click .expand-arrow' : 'expandDetailsClick',
            'click .expand-view' : 'expandDetailsClick',
            'blur .required': 'requiredBlur'
        },

        /**
         * Initialize view.
         */
        initialize: function(options) {
            options=$.extend(true, {
                type:false
            }, options);

            this.statusi= {
                A  : 'En Route',
                C  : 'Canceled',
                D  : 'Diverted',
                DN : 'Data source needed',
                L  : 'Landed',
                NO : 'Not Operational',
                R  : 'Redirected',
                S  : 'Scheduled',
                U  : 'Unknown'
            };

            this.searchResultsTemplate = $('#search-results-template');

            var h = new Date();
            h = h.getHours();
            if (h % 2 !== 0) {
                h = h + 1;
            }
            this.$('#flightTime').val(h);

            _.bindAll(this, 'renderResults', 'flightStatsSearch');

            PubSub.on('popup:click', this.flightStatsSearch);

            //calls super method
            BaseView.prototype.initialize.call(this, options);

            var activeForm=false;
            var forms = this.$('form');
            _.each(forms, function(item, index){
                this.subviews['flightSearchForm' + index] = new FormView({
                    el: $(item)
                });
                if($(item).hasClass('flight-tracker-form-active')) {
                    activeForm=$(item).data('search-type');
                }

                var parentIndex = index;
                _.each($(item).find('.airport-code'), _.bind(function(item, index){
                    this.subviews['flightSearchAutoComplete' + parentIndex + '-' + index] = new AutoComplete({
                        el: $(item),
                        maxResults: 6,
                        resultDisplayTemplate: '<%= abbr %> - <%= name %>',
                        resultValueTemplate: '<%= abbr %>',
                        url: '/services/flightstats/airports/search/'
                    });
                }, this));
                _.each($(item).find('.airline-code'), _.bind(function(item, index){
                    this.subviews['flightSearchAutoComplete' + parentIndex + '-' + index] = new AutoComplete({
                        el: $(item),
                        maxResults: 6,
                        resultDisplayTemplate: '<%= abbr %> - <%= name %>',
                        resultValueTemplate: '<%= abbr %>',
                        url: '/services/flightstats/airlines/search/'
                    });
                }, this));
            }, this);

            if(activeForm) {
                this.options.type=activeForm;
            }

            if(!this.options.type) {
                this.options.type='flight';
            }

            this.currentSearchType = this.options.type;
            this.$('.flight-tracker-'+this.options.type+'-form-wrap').addClass('flight-tracker-form-active');
            this.$('.flight-tracker-search-btn.'+this.options.type).addClass('active');

        },

        flightSearchFormSubmit: function(e) {
            var form = $(e.currentTarget);
            var errors = 0;
            form.find('.required').each(function(){
                var $t = $(this);
                if ($t.val() === '') {
                    $t.addClass('input-error');
                    errors++;
                }
            });
            if (errors !== 0) {
                return false;
            }

            if (!form.attr('action')) {
                e.preventDefault();
                var formValues = {};
                _.each(form.serializeArray(), function(obj){
                    formValues[obj.name] = obj.value;
                }, this);
                this.flightStatsSearch(this.currentSearchType, formValues);
            }
            PubSub.trigger('uotrack', 'flighttrackermap');
        },

        /**
         * Build url
         * @param {String} searchType
         * @param {Object} params Object of optional parameters
         */
        getFlightSearchUrl: function(searchType, params){
            var url = this.$el.attr('data-fs-baseurl') + 'flightstatus/rest/v2/jsonp/',
                appId = this.$el.attr('data-fs-appid'),
                appKey = this.$el.attr('data-fs-appkey'),
                date = new Date(),
                year = date.getFullYear(),
                day = date.getDate(),
                month = date.getMonth() + 1,
                hour = date.getHours(),
                ymd = year + '/' + month + '/' + day,
                baseParams = '?appId=' + appId + '&appKey=' + appKey + '&extendedOptions=useInlinedReferences';

            if (searchType === 'flight') {
                url += 'flight/status/' + params.airline_name + '/' + params.flight_number + '/dep/' + ymd + baseParams;
            } else if (searchType === 'route') {
                url += 'route/status/' + params.origin_airport + '/' + params.dest_airport + '/dep/' + ymd + baseParams + '&utc=false&maxFlights=100';
            } else if (searchType === 'airport') {
                if (_.isUndefined(params.flight_time)) {
                    params.flight_time = hour;
                }
                url += 'airport/status/' + params.airport_code + '/' + params.flight_type + '/' + ymd + '/' + params.flight_time + baseParams + '&numHours=2';
            } else {
                url = '';
            }
            return url;
        },

        /**
         * Perform flight search
         * @param {String} searchType
         * @param {Object} params Object of optional parameters
         */
        flightStatsSearch: function(searchType, params) {
            var url = this.getFlightSearchUrl(searchType, params);
            // if data is currently being fetched, we need to stop it
            if (this.fetch) {
                this.fetch.abort();
            }
            this.fetch = StateManager.fetchData(url, { dataType: 'jsonp' }).done(_.bind(function(data) {
                    this.renderResults(data.flightStatuses, searchType, params);
                }, this)).fail(_.bind(function(){
                    this.$('.flight-tracker-results').html('<div class="error">There is no matching flight data.</div>');
                },this));

        },

        flightSearchButtonClick: function(e) {
            var clickedItem = $(e.currentTarget),
                newSearchType = clickedItem.attr('data-search-type');
            if(this.currentSearchType !== newSearchType) {
                this.$('.flight-tracker-search-btn').removeClass('active');
                clickedItem.addClass('active');
                this.$('.flight-tracker-' + this.currentSearchType + '-form-wrap').removeClass('flight-tracker-form-active');
                this.$('.flight-tracker-' + newSearchType + '-form-wrap').addClass('flight-tracker-form-active');
                this.currentSearchType = newSearchType;
            }
        },

        requiredBlur: function(e) {
            var $t = $(e.currentTarget);
            if ($t.val() !== '') {
                $t.removeClass('input-error');
            }
        },

        renderResults: function (results, type, params) {
            var statusi = this.statusi;
            _.each(results, function(result) {
                result.status = statusi[result.status];
                result.color = 'green';
                if(!_.isUndefined(result.delays)) {
                    var overallDelay = 0;
                    _.each(result.delays, function(delay) {
                        overallDelay += delay;
                    });
                    result.delays = overallDelay + " min";
                    result.color = 'yellow';
                }
                else {
                    result.delays = 'On-time';
                }
                if(result.status === 'Canceled') {
                    result.color = 'red';
                }
                if(_.isUndefined(result.departureAirport.stateCode)) {
                    result.departureAirport.stateCode = result.departureAirport.countryCode;
                }
                if(_.isUndefined(result.arrivalAirport.stateCode)) {
                    result.arrivalAirport.stateCode = result.arrivalAirport.countryCode;
                }
            });
            if(results.length) {
                results = { results : results };
                var list = _.template(this.searchResultsTemplate.html(), results);
                var resultsTitle = 'Results for ' + type + ' search:';
                if (params.flight_type_full && params.airport_name) {
                    resultsTitle = params.flight_type_full + ': ' + params.airport_name;
                }
                this.$('.flight-tracker-results').empty().append('<div class="search-title">' + resultsTitle + '</div>').append(list);
            }
            else {
                this.$('.flight-tracker-results').html('<div class="error">No matching flight data found.</div>');
            }
        },

        expandDetailsClick: function(e) {
            var flightId = $(e.target).attr('data-flightid');
            var $detailView = this.$('.detail-view-' + flightId);
            if(!$detailView.hasClass('open')) {
                $detailView.show().addClass('open');
                $(e.target).addClass('active');
            }
            else {
                $detailView.hide().removeClass('open');
                $(e.target).removeClass('active');
            }
        }

    });
    return FlightSearchView;
});
/**
 * @fileoverview Hotelme view module.
 * @author rmendez@gannett.com (Rotty Mendez)
 */
define('views/modules/travel/hotelme-module',[
    'jquery',
    'underscore',
    'backbone',
    'state',
    'pubsub',
    'baseview'
],
function(
    $,
    _,
    Backbone,
    StateManager,
    PubSub,
    BaseView
) {
        /**
         * View class.
         */
        var hotelmeView = BaseView.extend({

            /**
             * Initialize view.
             * @param {object} options to pass in module options
             */
            initialize: function(options) { 
                StateManager.fetchHtml('/services/travel/hotelme/').done(_.bind(function(html){
                    this.$el.html(html);
                }, this));

                BaseView.prototype.initialize.call(this, options);
            }

        });

        /**
         * Return view class.
         */
        return hotelmeView;
    }
);


/**
 * @fileoverview Homepage view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 *
 * GenericSectionView extends BasePage (view/pages/base-page.js).
 * If you require to override any of BasePage's methods please
 * ensure you called it's super method using the same technique
 * demonstrated in the initialize method:
 * BasePage.prototype.[overridden method name].apply(this, arguments);
 *
 */
define('views/pages/generic-section',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'views/pages/base-page',
    'views/modules/twitter',
    'views/modules/featured-content',
    'views/modules/blogs',
    'views/modules/quick-links',
    'views/modules/lottery',
    'views/modules/travel/kayak-module',
    'views/modules/travel/flight-search',
    'views/modules/travel/hotelme-module'
],
function(
    $,
    _,
    Backbone,
    App,
    PubSub,
    BasePage,
    TwitterView,
    FeaturedContent,
    Blogs,
    QuickLinks,
    Lottery,
    Kayak,
    FlightSearch,
    hotelme
)
    {

        /**
         * View class.
         */
        var GenericSectionView = BasePage.extend({

            destroy: function(removeEl){
                this.destroyed = true;
                // call base class destroy
                BasePage.prototype.destroy.apply(this, arguments);
            },

            render: function() {
                // Initialize the Twitter Module.
                this.subviews.twitter = new TwitterView({
                    el : this.$('.twitter-module'),
                    num_tweets : 4,
                    columns: 2
                });

                // Generates the 'quick links' area in the suspender.
                this.subviews.quickLinks = new QuickLinks(this.options.section, this.$el);

                // Initialize the Lottery Module.
                if(this.$('.mod.lottery').length){
                    this.subviews.lottery = new Lottery({
                        el: this.$('.mod.lottery')
                    });
                }
                 // Initialize the Dcdeals Module.
                if(this.$('.mod.dcdeals').length){
                    require(['views/modules/dcdeals'], _.bind(function(Dcdeals){
                        if (!this.destroyed){
                            this.subviews.dcdeals = new Dcdeals();
                        }
                    }, this));
                }
                // Initialize the Shermansdeals Module.
                if(this.$('.mod.shermansdeals').length){
                    require(['views/modules/shermansdeals'], _.bind(function(Shermansdeals){
                        if (!this.destroyed){
                            this.subviews.shermans = new Shermansdeals();
                        }
                    }, this));
                }

                // Initialize the Featured Content module
                this.$('.featured-content').each(_.bind(function(idx, el){
                    this.subviews['featured' + idx] = new FeaturedContent({
                        el : el,
                        transition : {
                            interval : 15000
                        }
                    });
                }, this));

                //Initialize the Kayak module
                if(this.$('.kayak-wrapper').length){
                    this.subviews.kayak = new Kayak();
                }

                var $flightTrackerFormWrap = this.$('.flight-tracker-formwrapper');
                if ($flightTrackerFormWrap.length) {
                    this.subviews.flightSearch = new FlightSearch({
                        el: $flightTrackerFormWrap
                    });
                }

                //Initialize the Hotelme module 
                var $hotelMe = this.$('.hotelme-wrapper');
                if ($hotelMe.length){
                    this.subviews.hotelme = new hotelme({
                        el: $hotelMe
                    });
                }

                // Initialize the Blogs module
                this.subviews.blogs = new Blogs({
                    el : this.$('.mod.blogs')
                });

                BasePage.prototype.render.apply(this, arguments);
            }

        });

        return GenericSectionView;
    }
);

/**
 * @fileoverview Ajax Widget module view. Dynamically loads an HTML snippet,
 * appending it to this.el
 * @author jhensley
 */
define('views/modules/ajax-widget',['jquery', 'underscore', 'backbone', 'state'],
    function($, _, Backbone, StateManager) {

        /**
         * View class.
         */
        var AjaxWidgetView = Backbone.View.extend({

            /**
             * Initialize view.
             * @param {Object} options View options passed in during init.
             */
            initialize: function(options) {

                var replace = $(this.options.contents).length > 0;
                this.loadData(this.options.url, replace);

                if (this.options.refresh && this.options.contents) {
                    this.refresh = setInterval(_.bind(function() {
                        this.loadData(this.options.url, true)
                    }, this), this.options.refresh)
                };

            },


            /**
             * Load ajax contents.
             * @param {string} url is the string of the url to parse.
             * @param {Boolean} replace is a flag to determine whether or not to
             * replace the existing contents/module
             */
            loadData: function(url, replace) {

                if ($(this.options.contents).hasClass('paused')) {
                    clearInterval(this.refresh);
                    return;
                };
                this.ajax = StateManager.fetchHtml(url).done(_.bind(function(htmlFrag){
                    this.ajax = null;
                    this.$el.html(htmlFrag);
                }, this)).always(_.bind(function(){
                    this.$el.removeClass('loading');
                }, this));

            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.undelegateEvents();
                if (this.ajax){
                    this.ajax.abort();
                }
                clearInterval(this.refresh);
                if (removeEl) this.remove();
            }

        });


        /**
         * Return view class.
         */
        return AjaxWidgetView;
    }
);

/**
 * @fileoverview Money markets stock lookup.
 * @author Mark Kennedy <mdkennedy@gannett.com>
 */
define('views/modules/money/stock-lookup',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'app',
    'views/modules/form/autocomplete'
],
    function(
        $,
        _,
        BaseView,
        StateManager,
        App,
        AutoComplete
        ) {
        
        /**
         * View class.
         */
        var StockLookupView = BaseView.extend({

            el: '.money-markets-tool-search-form',

            events: {
                'submit': 'onFormSubmit'
            },

            /**
             * Initialize view.
             */
            initialize: function(options) {
                BaseView.prototype.initialize.call(this,options);

                _.bindAll(this, 'onStockSelect');

                this.$lookupInput = this.$('.money-markets-stock-lookup-input');
                this.subviews.autocomplete = new AutoComplete({
                    el: this.$lookupInput,
                    resultDisplayTemplate: '<%= Symbol %> - <%= Name %>',
                    resultValueTemplate: '<%= Symbol %>',
                    onSelect: this.onStockSelect
                });
            },

            /**
             * When a stock result autocomplete item is selected.
             * @param {String} value Selected item data
             * @param {Object} data Selected item data
             */
            onStockSelect: function(value, data){
                var stockUrlPath = this.parseStockPath(data.SymbolType);
                this.setStockPath(stockUrlPath);
                this.$el.submit();
            },

            setStockPath: function(stockSymbol){
                this.$$('.money-markets-stock-lookup-path-input').val(stockSymbol);
            },
            getStockPath: function(){
                return this.$$('.money-markets-stock-lookup-path-input').val();
            },

            /**
             * given a symbol type, will determine the stock path for it
             * @param {String} symbolType
             * @returns {*}
             */
            parseStockPath: function(symbolType){
                var dataPath = 'stocks';
                if (symbolType) {
                    switch(symbolType) {
                        case 'C':
                            dataPath = 'stocks';
                            break;
                        case 'F':
                            dataPath = 'mutual-funds';
                            break;
                        case 'G':
                            dataPath = 'etfs';
                            break;
                    }
                }
                return dataPath;
            },

            /**
             * Checks if we have the stock path yet, if not, parses it
             * @param {Event} e form submit event
             */
            onFormSubmit: function(e){
                if (!this.getStockPath()) {
                    e.preventDefault();
                    if (this.$lookupInput.val()){
                        var stockValue = this.$lookupInput.val().toUpperCase();
                        StateManager.fetchData(this.$lookupInput.data('autocomplete-url') + stockValue).done(_.bind(function(data){
                            if (data && data.length){
                                // we need to filter our data object when there are multiple data sets
                                _.each(data,function(obj){
                                    if (obj.Symbol === stockValue) {
                                        this.setStockPath(this.parseStockPath(obj.SymbolType));
                                        this.$lookupInput.val(stockValue);
                                    }
                                },this);
                                this.$el.submit();
                            }
                        }, this));
                        //TODO show the user an error for invalid stock ticker?
                    }
                }
            },

            destroy: function(removeEl){
                this.$$('.money-markets-stock-lookup-path-input').val('');
                this.$lookupInput.blur();
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return StockLookupView;
    }
);

/**
 * @fileoverview Markets search module view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define('views/modules/money/markets-tool',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'app',
    'views/modules/money/stock-lookup',
    'views/modules/ajax-widget'
],
    function(
        $,
        _,
        BaseView,
        StateManager,
        App,
        StockLookup,
        AjaxWidget
        ) {
        
        /**
         * View class.
         */
        var MarketsSearchView = BaseView.extend({

            /**
             * Initialize view.
             */
            initialize: function(options) {
                BaseView.prototype.initialize.call(this,options);

                this.subviews.markets = new AjaxWidget({
                    el : this.$('.money-markets-tool-default-quotes'),
                    url : '/services/markets/default-quotes/',
                    refresh : 60000,
                    contents : ".money-markets-tool-default-quotes-item"
                });
                this.subviews.stockLookup = new StockLookup({
                    el: this.$('.money-markets-tool-search-form')
                });
            }

        });

        /**
         * Return view class.
         */
        return MarketsSearchView;
    }
);


/**
 * @fileoverview Job search module.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/money/job-search',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'form'
],
    function(
        $,
        _,
        BaseView,
        StateManager,
        FormView
        ) {
        
        /**
         * View class.
         */
        var JobSearchView = BaseView.extend({

            /**
             * Initialize the view.
             */
            initialize: function(options) {
                BaseView.prototype.initialize.call(this, options);

                // Do not use "fetchHtml".  This service returns an html fragment.  IE intereprets it as invalid html and throws it away.  Use fetchData instead.
                StateManager.fetchData('/services/money/jobs/categories/', { timeout: 10000 }).done(_.bind(function(html){
                    this.$('.jobs-form-dropdown').html(html);
                }, this))
                .always(_.bind(function(){
                    this.subviews.jobSearchForm = new FormView({
                        el: this.$('.jobs-form-wrap')
                    });
                }, this));
            }
        });

        /**
         * Return view class.
         */
        return JobSearchView;
    }
);


/**
 * @fileoverview Car search module.
 * @author mdkennedy@gannett.com (Mark Kennedy)
 *
 */

define('views/modules/money/car-search',[
    'jquery',
    'underscore',
    'baseview',
    'state',
    'form'
],
    function(
        $,
        _,
        BaseView,
        StateManager,
        FormView
        ) {
        
        /**
         * View class.
         */
        var CarSearchView = BaseView.extend({

            events: {
                'submit .cars-form-wrap': 'onFormSubmit'
            },

            /**
             * Initialize the view.
             */
            initialize: function(options) {
                BaseView.prototype.initialize.call(this, options);
                _.bindAll(this, 'onNewUsedToggleSelect', 'onMakeDropdownSelect', 'onModelDropdownSelect');

                // cache baseform url for later use
                this.form = this.$('.cars-form-wrap');
                this.baseFormUrl = this.form.attr('action');
                this.form.attr('action', this._buildFormUrl(this.baseFormUrl));

                this.subviews.carSearchForm = new FormView({
                    el: this.form,
                    formOptions: [{
                        el: this.$('.cars-make-dropdown'),
                        onSelect: this.onMakeDropdownSelect
                    },{
                        el: this.$('.cars-model-dropdown'),
                        onSelect: this.onModelDropdownSelect
                    },{
                        el: this.$('.cars-new-used-toggle'),
                        onSelect: this.onNewUsedToggleSelect
                    }]
                });

            },

            /**
             * When new/used toggle is selected.
             * @param {String} dataValue selected data value
             * @param {String} displayValue selected display value
             */
            onNewUsedToggleSelect: function(dataValue, displayValue){
                var selectedVal = _.escape(displayValue.toLowerCase()),
                    dropdownDataUrl = '/services/cars/dropdown/' + selectedVal + '/all';

                // populate 'make' and 'model' dropdowns based on new/used selection
                StateManager.fetchHtml(dropdownDataUrl).done(_.bind(function(html){
                    this.parseDropdown('select_dropdown1', html);
                    var modelDropdownResetHtml = this.getDropdownResetHtml('All Models');
                    this.parseDropdown('select_dropdown2', modelDropdownResetHtml);
                },this));

                // Set hidden fields based on selection of new/used
                this.setNewUsedHiddenValues(selectedVal);
                this.form.attr('action', this._buildFormUrl(this.baseFormUrl));
            },

            /**
             * Builds form url (aka 'action' attr)
             * @param {String} baseUrl the base url of the form
             * @returns {*}
             * @private
             */
            _buildFormUrl: function(baseUrl){
                // process a different form url based on new/used selection
                var newUsedToggleValue = this.$('#cars-form-new-used-select').val(),
                    url = baseUrl;
                if (newUsedToggleValue === 'used') {
                    url += 'for-sale/searchresults.action';
                } else {
                    url += 'go/search/newBuyIndex.jsp';
                }
                return url;
            },

            /**
             * Sets new/used hidden fields
             * @param {String} inputVal 'new' or 'used'
             */
            setNewUsedHiddenValues: function(inputVal){
                if (inputVal === "used") {
                    this.$("input:hidden[name='stkTyp']").attr('value', 'U');
                    this.$("input:hidden[name='tracktype']").attr('value', 'usedcc');
                } else {
                    this.$("input:hidden[name='stkTyp']").attr('value', 'N');
                    this.$("input:hidden[name='tracktype']").attr('value', 'newcc');
                }
            },

            /**
             * Creates a string to reset the dropdown to a single option of All Makes/Models
             * @param {String} displayValue
             */
            getDropdownResetHtml: function(displayValue) {
                return '<option class="uotrack" value="All" selected="selected">' + displayValue + '</option>';
            },

            /**
             * When an item from the 'make' dropdown is selected
             * @param {String} selectedDataValue
             * @param {String} selectedDisplayValue
             */
            onMakeDropdownSelect: function(selectedDataValue, selectedDisplayValue){
                var newUsedToggleValue = this.$('#cars-form-new-used-select').val(),
                    urlMakeValue,
                    url;
                if (selectedDataValue === 'All') {
                    urlMakeValue = 'All';
                } else {
                    urlMakeValue = selectedDisplayValue
                }
                
                url = '/services/cars/dropdown/' + newUsedToggleValue + '/' + _.escape(urlMakeValue.toLowerCase());

                // populate 'model' dropdown based on selected value
                StateManager.fetchHtml(url).done(_.bind(function(html){
                    if (selectedDataValue === 'All') {
                        var resetHtml = this.getDropdownResetHtml('All Models');
                        this.parseDropdown('select_dropdown2', resetHtml);
                    } else {
                        this.parseDropdown('select_dropdown2', html);
                    }
                },this));
                this.setMakeHiddenValues(selectedDataValue, selectedDisplayValue);
            },

            /**
             * When an item from the 'model' dropdown is selected
             */
            onModelDropdownSelect: function(selectedDataValue, selectedDisplayValue){
                this.setModelHiddenValues(selectedDataValue, selectedDisplayValue);
            },

            /**
             * Sets hidden values for 'make' selections
             * @param dataValue
             * @param displayValue
             */
            setMakeHiddenValues: function(dataValue, displayValue){
                this.$("input:hidden[name='AmbMkId']").val(dataValue);
                this.$("input:hidden[name='AmbMkNm']").val(displayValue);
                this.$("input:hidden[name='mkId']").val(dataValue);
            },

            /**
             * Sets hidden values for 'model' selections
             * @param dataValue
             * @param displayValue
             */
            setModelHiddenValues: function(dataValue, displayValue){
                this.$("input:hidden[name='AmbMdId']").val(dataValue);
                this.$("input:hidden[name='AmbMdNm']").val(displayValue);
                this.$("input:hidden[name='mdId']").val(dataValue);
            },

            /**
             * Build dropdown elements for selected dropdown/subviewName
             * @param {String} subviewName
             * @param {String} html
             */
            parseDropdown: function(subviewName, html) {
                this.subviews.carSearchForm.subviews[subviewName].refresh(html);
            },

            /**
             * When form is submitted
             * @param e
             */
            onFormSubmit: function(e){
                // if zipcode input field is not filled out or is invalid, alert the user by adding an error class
                var zipCodeInput = this.$('.cars-form-input-zip'),
                    validZipRegex = /^\d{5}(?:[-\s]\d{4})?$/, // Regex for valid zip (12345, 12345-6789, or 12345 6789)
                    selectedMake = this.$('#cars-form-make-select option:selected').val(),
                    selectedModel = this.$('#cars-form-model-select option:selected').val();
                if (!validZipRegex.test(zipCodeInput.val())) {
                    e.preventDefault();
                    zipCodeInput.addClass('ui-form-error');
                } else {
                    zipCodeInput.removeClass('ui-form-error');
                }
                // Remove the value if set to all on form submit because Cars.com prefers NOT to receive a value, than to receive "All"
                if (selectedMake === 'All') {
                    this.$('#cars-form-make-select option:selected').removeAttr('value');
                    this.setMakeHiddenValues('','');
                }
                if (selectedModel === 'All') {
                    this.$('#cars-form-model-select option:selected').removeAttr('value');
                    this.setModelHiddenValues('','');
                }
            },

            destroy: function(removeEl){
                // set base form's url back to original
                this.form.attr('action', this.baseFormUrl);
                BaseView.prototype.destroy.call(this, removeEl);
            }

        });

        /**
         * Return view class.
         */
        return CarSearchView;
    }
);

/**
 * @fileoverview Money view.
 *
 * HomeView extends BasePage (view/pages/base-page.js).
 * If you require to override any of BasePage's methods please
 * ensure you called it's super method using the same technique
 * demonstrated in the initialize method:
 * BasePage.prototype.[overridden method name].apply(this, arguments);
 *
 */

define('views/pages/money',[
    'jquery',
    'underscore',
    'app',
    'views/pages/generic-section',
    'views/modules/form/autocomplete',
    'views/modules/ajax-widget',
    'views/modules/money/markets-tool',
    'views/modules/money/job-search',
    'views/modules/money/car-search'
],
function(
    $,
    _,
    App,
    GenericSection,
    AutoComplete,
    AjaxWidget,
    MarketsTool,
    JobSearchView,
    CarSearchView
)
    {

        /**
         * View class.
         */
        var MoneyView = GenericSection.extend({

            /**
             * Load data.
             */
            render: function() {

                GenericSection.prototype.render.apply(this, arguments);

                this.$('.money-markets-tool-wrap').each(_.bind(function(idx, el){
                    this.subviews['marketsSearch' + idx] = new MarketsTool({
                        el: el
                    });
                }, this));

                this.$('.job-search-module').each(_.bind(function(idx, el){
                    this.subviews['jobSearch' + idx] = new JobSearchView({
                        el: el
                    });
                }, this));

                this.$('.car-search-module').each(_.bind(function(idx, el){
                    this.subviews['carSearch' + idx] = new CarSearchView({
                        el: el
                    });
                }, this));
            }
        });

        /**
         * Return view class.
         */
        return MoneyView;
    }
);

/**
 * @fileoverview Snapshots view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define('views/modules/snapshots',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'state',
    'cookie'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    StateManager
) {


    /**
     * View class.
     */
    var SnapshotsView = Backbone.View.extend({

        el: '.front-galleries',

        // Events.
        events: {
            'click a.vote' : 'revealQuickQuestion',
            'click .snap-vote a.cancel' : 'revealSnapshotTeaser',
            'click a.snap-vote-btn' : 'registerVote'
        },

        /**
         * Initialize view.
         */
        initialize: function() {
            this.subviews = {};

            this.render();
        },

        /**
         * Render the module.
         */
        render: function() {
            //check for if snapshots already exisits
            if($("#snapshots").length <= 0){
                var injectLoc = $('#CList-galleries ul li:first-child');
                injectLoc.after('<li data-id="gallery" id="snapshots" class="clst-item clst-item-link-styles clst-item suspender" data-href="/services/snapshots/gallery/"><a class="clst-link" href="/services/snapshots/gallery/" data-href="/services/snapshots/gallery/">Snapshots</a></li>');
            }
        },

        /**
         * Reveal the QuickQuestion pane where you can vote
         * @param {object} e is the element triggering this function
         */
        revealQuickQuestion: function(e) {
            var $question = $(e.currentTarget).closest('.snapshot-card');

            $('.snapshot', $question).hide();
            $('.snap-vote', $question).not('.results').fadeIn();
        },

        /**
         * Reveal the Snapshot teaser pane where you can vote
         * @param {object} e is the element triggering this function
         */
        revealSnapshotTeaser: function(e) {
            var $question = $(e.currentTarget).closest('.snapshot-card');

            $('.snap-vote', $question).hide();
            $('.snapshot', $question).fadeIn();
        },

        /**
         * Reveal the Snapshot teaser pane where you can vote
         * @param {object} e is the element triggering this function
         * @param {string} htmlFrag is the javascript rendered template fragment
         */
        revealResults: function(e, htmlFrag) {
            var $question = $(e.currentTarget).closest('.snapshot-card');

            if ($question.find('.snap-vote.results').length) {
                $question.find('.snap-vote.results').replaceWith(htmlFrag);
            } else {
                $question.append(htmlFrag);
            }

            $('.snap-vote', $question).hide();
            $('.snap-vote.results', $question).fadeIn();
        },

        /**
         * Reveal the Snapshot teaser pane where you can vote
         * @param {object} e is the element triggering this function
         */
        registerVote: function(e) {
            var $question = $(e.currentTarget).closest('.snapshot-card'),
                answer = $(e.currentTarget).attr('data-answer-id'),
                url = '/services/snapshots/vote/' + answer + '/';

            $(e.currentTarget).addClass('loading');

            var snapID = $('.slide.active[data-qqid]', this.el).attr('data-qqid');

            if ($.cookie(snapID)) {
                url = '/services/snapshots/get/' + snapID + '/';
            };

            this.ajax = StateManager.fetchData(url).done(_.bind(function(data){
                var votes = _.pluck(data.question[0].location[0].answer, 'answerCount'),
                    total = _.reduce(votes, function(memo, num) {
                        return memo + parseFloat(num);
                    }, 0),
                    length = data.question[0].location[0].answer.length - 1,
                    total_percent = 0;

                _.each(data.question[0].location[0].answer, function(answer, i){

                    var percent = Math.round((parseFloat(answer.answerCount) / total) * 100)

                    // if on the last iteration - the percentage is all the others minus 100
                    // guaranteeing we never end up over 100 (i can haz math!)
                    if (i == length) {
                        percent = 100 - total_percent;
                    // otherwise increment the total percentage point
                    } else {
                        total_percent += percent;
                    };

                    answer['answerPercent'] = percent;
                })

                var $template = $('#snapshot-results'),
                    compiled = _.template($template.html(),{ data: data.question[0]});

                this.revealResults(e, compiled);

                $(e.currentTarget).removeClass('loading');

                $.cookie(snapID, true);

            }, this));

        },

        /**
         * Clean up view.
         * Removes event handlers and element (optionally).
         * @param {boolean} removeEl option to also remove View from DOM.
         */
        destroy: function(removeEl) {
            this.undelegateEvents();
            _.each(this.subviews, function(view){
                if (typeof view.destroy !== 'undefined') {
                    view.destroy(removeEl);
                }
            });
            if (removeEl) {this.remove();}
        }

    });

    /**
     * Return view class.
     */
    return SnapshotsView;
});

/**
 * @fileoverview Markets module view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define('views/modules/markets',[
    'jquery',
    'underscore',
    'backbone',
    'baseview',
    'views/modules/ajax-widget',
    'pubsub'
],
function(
    $,
    _,
    Backbone,
    BaseView,
    AjaxWidget,
    PubSub
) {

    /**
     * View class.
     */
    var MarketsView = BaseView.extend({

        el: '#CList-Markets',

       // Events.
        events: {
            'click .market':'changeMarketFocus'
        },

        /**
         * Initialize view.
         * @param {object} options to pass in module options
         */
        initialize: function(options) {
            this.subviews = {};
            this.subviews.markets = new AjaxWidget({
                el : this.$el,
                url : '/services/markets/home-widget/',
                refresh : 60000,
                contents : "#homepage-markets-widget"
            });
        },

        /**
         * Change the market in focus - to preview chart, etc.
         * @param {object} event that triggered the function
         */
        changeMarketFocus: function(event) {
            var $markets = this.$('.market');
            var $selected = $(event.currentTarget);
            $markets.removeClass('active');
            $selected.addClass('active');
        }

    });

    /**
     * Return view class.
     */
    return MarketsView;
});

/**
 * @fileoverview Markets module view.
 * @author Jonathan Hensley <jhensley@gannett.com>
 */
define('views/modules/set-homepage',['jquery', 'underscore', 'backbone', 'pubsub'],
    function($, _, Backbone, PubSub) {

        /**
         * View class.
         */
        var SetHomepageView = Backbone.View.extend({

            el: '.size-suspender:first',

           // Events.
            events: {
                'click .set-homepage':'setHomepage'
            },

            /**
             * Initialize view.
             * @param {object} options to pass in module options
             */
            initialize: function(options) {
                this.render();
            },

            /**
             * Render the button
             */
            render: function() {
                 if (document.all && $('.set-homepage').length === 0) {
                    this.$el.append('<div class="set-homepage">Set as my Home Page</div>');
                }
            },

            /**
             * Set the homepage
             */
            setHomepage: function() {
                if (document.all) {
                    document.body.style.behavior='url(#default#homepage)';
                    document.body.setHomePage('http://www.usatoday.com');
                }
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.undelegateEvents();
                if (removeEl) {this.remove();}
            }


        });

        /**
         * Return view class.
         */
        return SetHomepageView;
    }
);

/**
 * @fileoverview Homepage view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 *
 * HomeView extends BasePage (view/pages/base-page.js).
 * If you require to override any of BasePage's methods please
 * ensure you called it's super method using the same technique
 * demonstrated in the initialize method:
 * BasePage.prototype.[overridden method name].apply(this, arguments);
 *
 */

define('views/pages/home',[
    'jquery',
    'underscore',
    'views/pages/base-page',
    'views/modules/snapshots',
    'views/modules/markets',
    'views/modules/set-homepage',
    'views/modules/quick-links',
    'views/modules/featured-content'
],
function(
    $,
    _,
    BasePage,
    Snapshots,
    Markets,
    SetHomepage,
    QuickLinks,
    FeaturedContent
)
    {

        /**
         * View class.
         */
        var HomeView = BasePage.extend({

            /**
             * Load data.
             */
            render: function() {
                // initialize snapshots
                this.subviews.snapshots = new Snapshots();

                //calls super method
                BasePage.prototype.render.apply(this, arguments);

                // Check for markets, if found - instantiate Ajax Widget
                if($('.load-markets').length){
                    this.subviews.markets = new Markets();
                }

                // Initialize the Featured Content Module.
                this.$('.featured-content').each(_.bind(function(idx, el){
                    this.subviews['featured' + idx] = new FeaturedContent({
                        el : el,
                        transition : {
                            interval : 15000
                        }
                    });
                }, this));

                // Generates the 'quick links' area below markets.
                this.subviews.quickLinks = new QuickLinks('home', this.$el);

                // setTimeout of 0 to ensure that 'set home page' is appended after quick links.
                _.defer(_.bind(function() {
                    this.subviews.set_homepage = new SetHomepage();
                }, this));
            }
        });

        /**
         * Return view class.
         */
        return HomeView;
    }
);

/**
 * @fileoverview Builds an indexed ad position on the page
 *
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('indexedAdPosition',[
    'jquery',
    'underscore',
    'views/modules/partner/ad-position',
    'app',
    'admanager',
    'adLogger'
],
    function($, _, AdPosition, App, AdManager, AdLogger) {
        

        var IndexedAdPosition = AdPosition.extend({
            /**
             * Initializes the view
             * @param options = { aws, pageName, pageType [ blog, card, cover, media, overlay, topic ], url }
             */
            initialize: function(options) {
                options = $.extend({
                    // required options
                    targeting: {},
                    slotType: 'out' // out of page by default for legacy purposes, no reason it can't be 'in' page
                }, options);

                // call base class initialize
                AdPosition.prototype.initialize.call(this, options);
            },

            refreshPosition: function() {
                this.isAdReady = false;
                if (this.subviews.adSlot) {
                    this.destroyAdPlacement();
                    this.subviews.adSlot.refresh();
                }
            },

            getNextAdIndex: function(currentIndex) {
                var meterTrigger = this._getMeterTrigger();
                if (!meterTrigger || currentIndex < 1) {
                    // do not support ads on indexes 0 or below
                    return null;
                } else {
                    var delta = currentIndex % meterTrigger;
                    if (delta) {
                        return currentIndex + (meterTrigger - delta);
                    } else {
                        return currentIndex;
                    }
                }
            },

            /**
             * Overrides ad-position's adReady to prevent the ad from immediately showing
             * @override
             */
            adReady: function() {
                AdLogger.logDebug('AdPosition ready');
                this.isAdReady = true;
            },

            _getMeterTrigger: function() {
                var thresholdType,
                    meterTrigger,
                    adPlacement = this.options.adPlacement,
                    split = adPlacement.indexOf('/');
                if (split !== -1) {
                    thresholdType = adPlacement.substring(0, adPlacement.indexOf('/'));
                } else {
                    thresholdType = adPlacement;
                }
                if (thresholdType) {
                    meterTrigger = window.site_config.ADS.THRESHOLDS[thresholdType.toUpperCase()];
                }
                if (!meterTrigger) {
                    AdLogger.logError('shouldShowAd() called without any defined thresholds: ' + thresholdType);
                }
                return meterTrigger;
            },

            shouldShowAd: function(index) {
                var showAd = this.getNextAdIndex(index) === index;
                // build the slot if we haven't already to prepopulate it
                if (!this.subviews.adSlot) {
                    this.subviews.adSlot = AdManager.getAdSlot(this.options.adPlacement, this.options.targeting, this.options.adSizes, this, this.options.slotType);
                }
                if (showAd && !this.isAdReady) {
                    showAd = false;
                    // ad isn't ready to be shown, skip it and try again
                    AdLogger.logDebug('ad skipped due to no ad being delivered in time, refreshing slot');
                    this.refreshPosition();
                }
                AdLogger.logDebug('shouldShowAd: ' + showAd, this);
                return showAd;
            }
        });
        return IndexedAdPosition;
    });
/**
 * @fileoverview Cover View.
 * @author Chris Manning
 */
define('views/modules/coverview',[
    'jquery',
    'underscore',
    'backbone',
    'state',
    'pubsub',
    'app',
    'baseappview',
    'indexedAdPosition',
    'uiPageTurn'
],
function(
    $,
    _,
    Backbone,
    StateManager,
    PubSub,
    App,
    BaseAppView,
    IndexedAdPosition
)
    {
        /**
         * View class.
         */
        var CoverView = BaseAppView.extend({

            el: '#cover-view',

            events: {
                'click .prev': 'prevSlide',
                'click .ui-page-turn': 'palmSlide',
                'click .next': 'nextSlide'
            },

            initialize: function(options) {
                options = $.extend(true, {animation: {slideDuration: 350}}, options);

                _.bindAll(this, 'onPageTurn', 'resizeHandler');
                this.$body = App.get('body');
                this.$top = App.get('scrollEl');
                this.$doc = App.get('doc');
                this.$win = App.get('win');

                this.showingAd = false;

                this.flipTransformStyle = this.transformCssHyphenName + ' ' + options.animation.slideDuration + 'ms linear';

                var throttledResize = _.throttle(this.resizeHandler, 50);
                this.$win.on('resize.' + this.cid, throttledResize);

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            resizeHandler: function(){
                if (this.$pages) {
                    var winWidth = this.$win.width(),
                        winHeight = this.$win.height() - 40; // exclude top menubar
                    if (winWidth % 2){
                        this.$pages.addClass('width-wiggler');
                    } else {
                        this.$pages.removeClass('width-wiggler');
                    }
                    if (this.$adContents && this.subviews.ad){
                        this.$adContents.css({width: winWidth, top: 40, height: winHeight});
                        this.subviews.ad.resizeAd(winWidth, winHeight);
                    }
                }
            },

            palmSlide: function(e){
                // let clicks of stories through or the ad stuff
                var $target = $(e.target);
                if ($target.hasClass('load-story') || $target.hasClass('parent-label') || $target.closest('.partner-placement').length){
                    return;
                }
                var screenX = e.screenX;
                var midPoint = this.$win.width() >> 1;
                if (screenX > midPoint){
                    this.nextSlide(e);
                }else{
                    this.prevSlide(e);
                }
            },

            prevSlide: function(e) {
                if (e){e.preventDefault();}

                var currentIndex = this.$pages.uiPageTurn('getCurrentPage').index('.ui-page-turn:not(.partner-placement)'),
                    // this needs to be - 2 because we want to insert the ad before the index of the ad
                    adAction = this.shouldShowAd(currentIndex, 'before');
                this.registerAnimation(this.$pages.uiPageTurn('prevPage')).done(function() {
                    if (adAction){
                        adAction();
                    }
                });
                PubSub.trigger('heattrack', 'thebigpageleft');
            },

            nextSlide: function(e) {
                if (e){e.preventDefault();}

                var currentIndex = this.$pages.uiPageTurn('getCurrentPage').index('.ui-page-turn:not(.partner-placement)'),
                    adAction = this.shouldShowAd(currentIndex + 1, 'after');
                this.registerAnimation(this.$pages.uiPageTurn('nextPage')).done(function(){
                    if (adAction){
                        adAction();
                    }
                });
                PubSub.trigger('heattrack', 'thebigpageright');
            },

            shouldShowAd: function(index, direction) {
                var ad = this.subviews.ad;
                if (!this.showingAd && ad && ad.shouldShowAd(index)) {
                    this.showingAd = true;
                    this.$pages.uiPageTurn('getCurrentPage')[direction](this.$adSlide);
                    return _.bind(ad.playAd, ad);
                } else if (this.showingAd) {
                    this.showingAd = false;
                    this.subviews.ad.stopAd();
                    return _.bind(ad.refreshPosition, ad);
                }
            },

            slideTransition: function($newSlide, left){
                $newSlide.addClass('active');
                if (left){
                    $newSlide.css('left', '100%');
                } else {
                    $newSlide.css('left', '-100%');
                }
                this.animate($newSlide, 'left', 0, this.options.animation.slideDuration, 'linear')
                    .done(_.bind(function(){
                        this.$activePage = $newSlide;
                        this.busy = false;
                    }, this));
                this.$activePage.css('left', '0%');
                this.animate(this.$activePage, 'left', (left ? '-100%': '100%'), this.options.animation.slideDuration, 'linear');
            },

            setFixedPosition: function(offset){
                BaseAppView.prototype.setFixedPosition.call(this, 0);
            },

            setupAds: function() {
                var pageInfoObj = StateManager.getCurrentPageInfo();
                this.$adSlide = this.$('.partner-coverview-ad');
                this.$adContents = this.$('.partner-coverview-contents');
                this.subviews.ad = new IndexedAdPosition({
                    el: this.$adContents,
                    adPlacement: 'coverview/' + pageInfoObj.aws,
                    adSizes: ['coverviewfullpage'],
                    targeting: {
                        'title' : pageInfoObj.seotitletag,
                        'sitePage' : 'usat/' + (pageInfoObj.ssts || '').replace(/\/\/*$/, '')
                    }
                });
            },

            keyboardShortcuts: function(e) {
                if (e.which === 37) {
                    this.prevSlide(e);
                } else if (e.which === 39) {
                    this.nextSlide();
                }
            },

            afterPageReveal: function(fromPath, toPath, paused) {
                _.bindAll(this, 'keyboardShortcuts');
                this.$prev = this.$('.prev');
                this.$next = this.$('.next');
                this.$pages = this.$('#cover-view-pages');
                this.$pages.uiPageTurn({
                    onPageTurn: this.onPageTurn,
                    turnDuration: 600,
                    fallback: 'slide',
                    shadow: false // Browser can't handle shadow for large viewports.
                });
                this.setupAds();
                this.resizeHandler();
                this.$doc.on('keyup.' + this.cid, this.keyboardShortcuts);
                this.trackPageChange(this.$('.ui-page-turn.active'));
            },

            onPageTurn: function($el){
                if ($el.prev('.ui-page-turn').length){
                    this.$prev.show();
                }else{
                    this.$prev.hide();
                }
                if ($el.next('.ui-page-turn').length){
                    this.$next.show();
                }else{
                    this.$next.hide();
                }
                this.trackPageChange($el);
            },

            setPage: function(fromPath, toPath, paused, htmlFrag) {
                /* coverview is special, so turn off regular analytics
                 * let .trackPageChange() deal with analytics
                 * Use the super setPage method, just guarantee that it is 'paused'
                 */
                 BaseAppView.prototype.setPage.call(this, fromPath, toPath, true, htmlFrag);
            },

            trackPageChange: function(page){
                //fakes pageload event per visible page
                var coverInfo = page.find('span.coverInfo').text() || {};
                var coverInfObj = $.parseJSON(coverInfo) || {};
                App.set('pagename', coverInfObj.pagename);  // FIXME - get rid of App.set/App.get (but not when it's last minute qa push)
                App.set('seotitle', coverInfObj.seotitle);
                App.set('ssts', coverInfObj.ssts);
                App.set('aws', coverInfObj.aws);
                App.set('url', 'http://www.usatoday.com/' + Backbone.history.fragment);
                App.set('contenttype', coverInfObj.contenttype);
                this.pageInfo= {
                    pagename: App.get('pagename'),
                    seotitle: App.get('seotitle'),
                    ssts: App.get('ssts'),
                    aws: App.get('aws'),
                    url: App.get('url'),
                    contenttype: App.get('contenttype')
                };
                PubSub.trigger('page:load', this.pageInfo);
            },

            getRevealAppLoader: function(){
                return '<section id="cover-view" class="ui-loading dark-medium"></section>';
            },

            activateLoader: function(){
                // empty cause we have our own loader in getRevealAppLoader() and no other loaders are needed
            },

            destroy: function() {
                this.$doc.off('.' + this.cid);
                this.$win.off('.' + this.cid);
                BaseAppView.prototype.destroy.apply(this, arguments);
            }

        });

        /**
         * Return view class.
         */
        return CoverView;
    }
);

/*
 * Disable document.write, except for well formed references to remote scripts
 */
(function() {
    /* These should never be needed:
     var orig= {
     write: document.write,
     writeln: document.writeln
     };
     */
    var onwrite= {};
    var onscript= {};
    document.writeln= (self.console||{}).log || function() {};
    document.write= function() {
        for (var p in onwrite) {
            if (onwrite.hasOwnProperty(p)) {
                try {
                    onwrite[p].apply({}, arguments);
                } catch (e) {}
            }
        }
        var text = Array.prototype.join.call(arguments, '');
        var valid= '<script[^<>]*src=[\'"]?([^\'"<> :/]*:*\/\/[a-z0-9.]*google\.com\/[^\'"<> ]*)[\'"]?[^<>]*>[^<>]*<\/script>';
        var all= new RegExp(valid, 'gi');
        var one= new RegExp(valid, 'i');
        var scripts= text.match(all) || [];
        for (var j= 0; j<scripts.length; j++) {
            scripts[j].match(one);
            $.ajax({
                cache: true,
                dataType: 'script',
                success: function() {
                    for (var p in onscript) {
                        if (onscript.hasOwnProperty(p)) {
                            try {
                                onscript[p].apply({}, arguments);
                            } catch (e) {}
                        }
                    }
                },
                url: RegExp.$1
            });
            text= text.replace(scripts[j], '');
        }
        if (!text.match(/^\s*$/)) {
            try {
                console.log("document.write ignoring ",text);
            } catch (e) {}
        }
    };
    document.write.addOnWrite= function(name, handler) {
        if ('function' != typeof handler) return;
        if (onwrite[name]) return;
        onwrite[name]= handler;
    };
    document.write.addOnScript= function(name, handler) {
        if ('function' != typeof handler) return;
        if (onscript[name]) return;
        onscript[name]= handler;
    };
    document.write.delOnWrite= function(name) {
        if (!delete onwrite[name]) onwrite[name]= undefined;
    };
    document.write.delOnScript= function(name) {
        if (!delete onscript[name]) onscript[name]= undefined;
    };
})();

define("documentWrite", function(){});

/**
 * @fileoverview Search view.
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
define('views/pages/search',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'baseappview',
    'state',
    'documentWrite'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    BaseAppView,
    StateManager
)
    {
        /**
         * View class.
         */
        var SearchView = BaseAppView.extend({

            // View element.
            el: '.search-results',

            // Events.
            events: {
                'click .grid-btn': 'gridView',
                'click .list-btn': 'listView',
                'click .close-search-btn': 'closeSearch'
            },

            /**
             * Initialize view.
             */
            initialize: function(options) {
                options = $.extend(true, {
                        delay: {
                            playlistAutoClose: 250
                        },
                        animations: {
                            open: {
                                duration: 250,
                                easing: 'ease-in-out'
                            },
                            close: {
                                duration: 250,
                                easing: 'ease-in-out'
                            }
                        }
                    }, options);

                // Cache references to common elements/calculations.
                this.win = App.get('win');
                this.body = App.get('body');
                this.scrollEl = App.get('scrollEl');

                // Sync masthead positioning with global header .js
                this.body.removeClass('show-search');
                PubSub.trigger('masthead:expand');

                // Scopes 'this' to window
                _.bindAll(this, 'lazyload');

                // Set initial view state.
                this.currentView = 'view-grid';

                this.init = false;
                this.requestInProgress = false;

                // Load initial images and set layload on scroll
                this.win.on('scroll.' + this.cid, _.throttle(this.lazyload, 200));

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            getRevealAppLoader: function(){
                return '<article class="search-results ui-loading dark-medium"></article>';
            },

            animateRevealApp: function(fromPath, toPath){
                if (fromPath == null){
                    return $.Deferred().resolve();
                }else{
                    this.$('#search-form').css('height','');
                    this.$el.css({opacity: 1, display: 'block', top: '-100%', height: '100%'});
                    var promise = this.animate(this.$el, 'top', '0%',
                        this.options.animations.open.duration,
                        this.options.animations.open.easing);
                    promise.done(_.bind(function(){
                        this.$el.css('height', '');
                        PubSub.trigger('open:searchResults');
                    }, this));
                    return promise;
                }
            },

            setFixedPosition: function(offset){
                PubSub.trigger('masthead:collapse');
                BaseAppView.prototype.setFixedPosition.apply(this, arguments);
            },
            clearFixedPosition: function(){
                PubSub.trigger('masthead:expand');
                BaseAppView.prototype.clearFixedPosition.apply(this, arguments);
            },

            animateRemoveApp: function(fromPath, toPath){
                var scrollPosition = App.getScrollPosition();
                this.$el.css({marginTop: -1 * scrollPosition,
                                height: this.win.height() + scrollPosition});
                this.$('.summary').css('position', 'absolute');
                this.scrollEl.scrollTop(0);
                return this.animate(this.$el, 'top', '-100%',
                    this.options.animations.close.duration,
                    this.options.animations.close.easing);
            },

            afterAppRemove: function(fromPath, toPath){
                PubSub.trigger('close:searchResults');
                PubSub.trigger('uotrack','searchResultsclose');
            },

            beforePageReveal: function(fromPath, toPath, htmlFrag){
                PubSub.trigger('open:searchResults');
            },

            afterPageReveal: function(fromPath, toPath){
                if (!this.init){
                    this.init = true;
                    // stash the original path so we know where we came from
                    this.originalPath = fromPath;
                }
                this.moreResultsPlacer = this.$('.more-results');
                this.lazyload();
                this.searchWrap = this.$('#search-form');
                this.searchTextInput = this.searchWrap.find('.text-input');
                this.setup();
                this.setupTextAd();
            },

            /**
             * Get more search results
             */
            getMoreResults: function(fetchUrl) {
                this.requestInProgress = true;
                StateManager.fetchHtml(fetchUrl).done(_.bind(function(htmlFrag){
                    this.moreResultsPlacer.parent().append(htmlFrag);
                    this.moreResultsPlacer.remove();
                    this.moreResultsPlacer = this.$('.more-results');
                }, this)).fail(_.bind(function(){
                    this.moreResultsPlacer.remove();
                    this.moreResultsPlacer = null;
                }, this)).always(_.bind(function(){
                    this.requestInProgress = false;
                }, this));
                return false;
            },

            getTerm: function() {
                return $('.search-term .term', this.$el).attr('data-term');
            },

            /**
             * Setup
             */
            setup: function() {
                this.results = this.$('.results');
                this.summary = this.$('.summary');

                this.sidebar = this.$('.sidebar');
                this.viewGrid = this.$('.grid-btn');
                this.viewList = this.$('.list-btn');

                if(this.currentView === 'view-list') {this.listView();}
            },

            setupTextAd : function() {
                // grab term
                var term = this.getTerm();
                // grab element
                var id = 'partner_search_text_ads' + new Date().getTime();
                $('.tile.ad', this.$el).attr('id', id);
                var pageOptions = { 
                  'pubId': 'partner-usatoday_js',
                  'query': term,
                  'hl': 'en'
                };

                var adblock1 = { 
                  'container': id,
                  //'number': '3', // Let Google decide
                  'lines': '3',
                  'fontFamily': 'arial',
                  'fontSizeTitle': '13px',
                  'fontSizeDescription': '12px',
                  'fontSizeDomainLink': '12px',
                  'colorTitleLink': '1EA3FF',
                  'colorText': 'FFFFFF',
                  'colorDomainLink': '00C641',
                  'colorBackground': '2C2C2C'
                };

                this.loadGoogleSearchAds(pageOptions, adblock1);
            },

            /**
             * Grid view
             */
            gridView: function() {
                this.viewGrid.addClass('active');
                this.viewList.removeClass('active');
                this.summary.removeClass('list').addClass('grid');
                this.results.removeClass('view-list').addClass('view-grid');
                this.currentView = 'view-grid';
                //Moving Google ads to bottom of sidebar in grid view
                $('.ad').appendTo('.sidebar');
                return false;
            },

            /**
             * List view
             */
            listView: function() {
                this.viewList.addClass('active');
                this.viewGrid.removeClass('active');
                this.summary.removeClass('grid').addClass('list');
                this.results.removeClass('view-grid').addClass('view-list');
                this.currentView = 'view-list';
                //Moving Google ads to top of main content in list view
                $('.ad').prependTo('.list-content');
                return false;
            },

            lazyload: function(){
                if (!this.init || !this.moreResultsPlacer || !this.moreResultsPlacer.length || this.requestInProgress){
                    // resize handler hit too soon, we haven't loaded yet
                    // there's no more results (no placer)
                    // there's already a request in progress
                    return;
                }
                var scrollY = App.getScrollPosition();
                var bodyH = this.body.height();
                if(this.moreResultsPlacer.offset().top <= (scrollY + bodyH)){
                    this.getMoreResults(this.moreResultsPlacer.data('href'));
                }
            },

            closeSearch: function(){
                StateManager.navigateToPreloadedUrl(this.originalPath);
            },

            /*
             * Massive hack to work around google's use of document.write (because document.write's spec is a massive hack)
             * redefined document.write is in main
             */
            loadGoogleSearchAds: function(pageOptions, adblock1) {
                var done= false;
                var ads= function() {
                        if (done) {
                            document.write.delOnWrite('searchads');
                            document.write.delOnScript('searchads');
                            return;
                        }
                        if (!self.google) return false;
                        if (!google.ads) return false;
                        if (!google.ads.search) return false;
                        if (!google.ads.search.Ads) return false;
                        done= new google.ads.search.Ads(pageOptions, adblock1);
                        document.write.delOnWrite('searchads');
                        document.write.delOnScript('searchads');
                    };
                if (!ads()) {
                    document.write.addOnWrite('searchads', ads);
                    document.write.addOnScript('searchads', ads);
                    $.ajax({
                        cache: true,
                        dataType: 'script',
                        success: ads,
                        url: 'http://www.google.com/adsense/search/ads.js'
                    });
                }
            },

            destroy: function() {
                document.write.delOnWrite('searchads');
                document.write.delOnScript('searchads');
                this.win.off('.' + this.cid);
                BaseAppView.prototype.destroy.apply(this, arguments);
            }
        });

        /**
         * Return view class.
         */
        return SearchView;
    }
);

/**
 * @fileoverview Handles the slider ad functionality.
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 * @author Chad Shryock <dshryock@gannett.com>
 */

define('views/modules/partner/slider',[
    'jquery',
    'underscore',
    'baseview',
    'sharedAdPosition'
],
function(
    $,
    _,
    BaseView,
    SharedAdPosition
) {
    
        /**
         * View class.
         */
        var SliderView = BaseView.extend({

            el: '.partner-slider-ad',
            /**
             * Events
             */
            events: {
                'click .partner-slider-close' : 'onClickCloseButton'
            },

            /**
             * Clean up the view (no argument).
             */
            destroy: function(removeEl) {
                this.stopCloseTimer();
                this.hide(true);
                // call base class initialize
                BaseView.prototype.destroy.call(this, false);
            },

            /**
             * Initialize view.
             */
            initialize: function(options) {
                _.bindAll(this, 'onAdReady');

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);

                this.subviews.ad = new SharedAdPosition({
                    el: this.$el,
                    adSizes: ['mediumrectangle', 'halfpage', 'portrait', 'filmstrip'],
                    adPlacement: 'high_impact',
                    adType: 'slider',
                    defaultPosition: true,
                    onAdReady: this.onAdReady
                });
            },

            onAdReady: function(){
                this.subviews.ad.showAd();
                this.show(true).done(_.bind(function(){
                    this.startCloseTimer();
                }, this));
            },

            onClickCloseButton: function(e) {
                e.preventDefault();
                this.destroy(false);
            },

            startCloseTimer: function() {
                var closeTime = window.site_config.ADS.SLIDER.CLOSETIME;
                if (closeTime) {
                    this.closeTimer = setTimeout(_.bind(function() {
                        this.hide();
                    }, this), closeTime);
                }
            },

            stopCloseTimer: function() {
                clearTimeout(this.closeTimer);
            }
        });

        /**
         * Return view class.
         */
        return SliderView;
    }
);

/**
 * @fileoverview Topic view.
 * @author kris.hedstrom@f-i.com (Kris Hedstrom)
 */
define('views/pages/stag-front',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'baseappview',
    'views/modules/partner/slider',
    'views/modules/partner/overlay-ad-fronts',
    'views/modules/footer',
    'views/modules/headline',
    'views/modules/video',
    'views/modules/carousel'
],
function(
    $,
    _,
    Backbone,
    App,
    PubSub,
    BaseAppView,
    SliderAd,
    OverlayAdFront,
    Footer,
    Headline,
    Video,
    Carousel
) {

    
        /**
         * View class.
         */
        var StagView = BaseAppView.extend({

            // Events.
            events: {
                'click .ui-btn': 'toggleHeadlineView'
            },

            /**
             * Initialize view.
             * @param {Object} options View options passed during init.
             */
            initialize: function(options) {
                this.$top = App.get('scrollEl');

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            beforePageReveal: function(fromPath, toPath, htmlFrag) {
                // Skin select element.
                // this.sortSelect = htmlFrag.find('#topic-sort-order');
            },

            afterPageReveal: function(fromPath, toPath) {
                App.set('currentCardPath', toPath);
                this._initializeTopic(fromPath, 'stag');
            },

            _initializeTopic: function(fromPath, pageType) {
                var _this = this;
                this.headlineCollection = this.$('.collection');
                this.toggleList = this.$('.list-btn');
                this.toggleGrid = this.$('.grid-btn');

                this.subviews.video = [];
                // Initialize each video as its own video instance.
                $('.stag.hero .video').each(function() {
                    var video = new Video({
                        // Use .video parent() because hero markup is different.
                        el: $(this).parent().get(0)
                    });
                    _this.subviews.video.push(video);
                });

                // Init footer.
                this.subviews.footer = new Footer();

                // Initialize the headline grid.
                this.subviews.headline = new Headline({
                    el: '.stag .mod.headlines'
                });

                // Initialize the gallery carousel.
                if (this.$('.mod.galleries').length) {
                    this.subviews.gallery = new Carousel({
                        ads: true,
                        el: '.stag .mod.galleries',
                        fullScreen: true,
                        track: true
                    });
                }

                this.subviews.overlayAd = new OverlayAdFront({
                    el: this.$('.partner-overlay'),
                    leaveBehindEl: this.$('.partner-leavebehind'),
                    isStagFront: true
                });

                this.subviews.sliderad = new SliderAd();
            },

            getRevealAppLoader: function() {
                return '<article id="stag-view" class="cards stag ui-loading dark-medium"></article>';
            },

            /**
             * Adjust the topic card to the top.
             */
            adjust: function() {
                this.$top.animate({scrollTop: 0}, 200);
            },

            /**
             * Toggle the headline view between grid and list.
             * @param {Event} event Click event.
             */
            toggleHeadlineView: function(event) {
                event.preventDefault();
                var currentTarget = $(event.currentTarget);
                if (currentTarget.hasClass('grid-btn')) {
                    //change to grid from list
                    this.headlineCollection.removeClass('listview').addClass('gridview');
                    currentTarget.addClass('active');
                    this.toggleList.removeClass('active');
                    App.lazyLoadImage(this.$('img'), 'data-grid-src', true);
                }
                else if (currentTarget.hasClass('list-btn')) {
                    //change to list from grid
                    this.headlineCollection.addClass('listview').removeClass('gridview');
                    currentTarget.addClass('active');
                    this.toggleGrid.removeClass('active');
                    App.lazyLoadImage(this.$('img'), 'data-list-src', true);
                }
            }

        });


        /**
         * Return view class.
         */
        return StagView;
    }
);

/**
 * @fileoverview Previous bar view.
 * @author stephen.burgess@f-i.com (Stephen Burgess)
 */
define('views/modules/previous-bar',[
    'jquery',
    'underscore',
    'backbone'
    ],
    function(
        $,
        _,
        Backbone
    ) {


        /**
         * View class.
         */
        var PreviousBarView = Backbone.View.extend({

            // View element.
            el: '.previous-bar',

            /**
             * Initialize view.
             * @param {Object} options View options passed during init.
             */
            initialize: function(options) {
                this.options = $.extend({}, options || {});
                var previousBar = $('.previous-bar').addClass('active');
                previousBar.find('.title').text(options.title);
                previousBar.attr('href', options.url);
            }

        });


        /**
         * Return view class.
         */
        return PreviousBarView;
    }
);

/**
 * @fileoverview Election Topic Page view.
 * @author stwilson@gannett.com (Stan Wilson) 
 */
define('views/pages/election-2012',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'baseview',
    'views/modules/form/autocomplete'
    ],
    function(
        $,
        _,
        Backbone,
        App,
        PubSub,
        BaseView,
        AutoComplete
    ) {


        /**
         * View class.
         */
        var ElectionView = BaseView.extend({

             // View element.
            el: '#topic-card',

            /**
            * Initialize view.
            */
            initialize: function (options) {

                this.$win = App.get('win');
                if( $("#election-results-fullscreen")  ){
                    this.onResize();
                    this.$win.on('resize.' + this.cid, this.onResize);
                }
                _.bindAll(this, 'onStateSelect');
                BaseView.prototype.initialize.call(this, options);
                this.$('.election-state-input').each(_.bind(function(idx, el){
                    this.subviews['stateAutocomplete' + idx] = new AutoComplete({
                        el : el,
                        resultDisplayTemplate: '<%= state %>',
                        resultValueTemplate: '<%= state %>',
                        onSelect: this.onStateSelect,
                        selectedInputValue: 'state'
                    });
                }, this));
            },
            /**
             * When an item is selected from autocomplete states.
             * @param {String} value Selected items data
             * @param {Object} data Selected items data
             */
            onStateSelect : function(value, data){
                var form = this.$('#election-state-nav-form');
                form.attr('action', data.link);
                form.submit();
            },

            onResize:function(){
                var newHeight = ( this.$win.height() > 620)?  this.$win.height() : 620;
                $("#election-results-fullscreen").height( newHeight  );
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {boolean} removeEl option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                this.$win.off('.' + this.cid, this.onResize);
                BaseView.prototype.destroy.call(this, removeEl);
            }
        });


        /**
         * Return view class.
         */
        return ElectionView;
    }
);

/**
 * @fileoverview Topic view.
 * @author kris.hedstrom@f-i.com (Kris Hedstrom)
 */
define('views/pages/topic',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'views/pages/stag-front',
    'views/modules/featured-content',
    'views/modules/previous-bar',
    'views/pages/election-2012',
    'views/modules/twitter'
    ],
function(
    $,
    _,
    Backbone,
    App,
    PubSub,
    StagFront,
    FeaturedContent,
    PreviousBar,
    ElectionView,
    TwitterView
    ) {


        /**
         * View class.
         */
        var TopicView = StagFront.extend({

            // View element.
            el: '#topic-card',

            _initializeTopic: function(fromPath, ignoredPageType){
                if(App.get('contenttype') == 'story') {
                    this.subviews.prevBar = new PreviousBar({
                        url: '/' + fromPath,
                        title: App.get('seotitle')
                    });
                }

                //calculations for size of featured content items / container
                var itemWidth = this.$('.mod.featured-content .paginator ul > li').outerWidth();
                var containerWidth = this.$('.mod.featured-content .paginator').outerWidth();
                var itemsPerView = containerWidth / itemWidth;
                var twitterMod = this.$('.mod.tweets');

                // Initialize the Featured Content module
                this.$('.featured-content').each(_.bind(function(idx, el){
                    this.subviews.featured = new FeaturedContent({
                        el : el,
                        itemWidth: 192,
                        itemsPerView: 5,
                        transition : {
                            interval : false
                        }
                    });
                }, this));
                this.subviews.election2012 = new ElectionView();


                // Initialize the Twitter Module.
                if(twitterMod.length > 0){
                    this.subviews.twitter = new TwitterView({
                        el : '.mod.tweets',
                        num_tweets : 9,
                        columns: 3
                    });
                }

                // call base class initialize
                StagFront.prototype._initializeTopic.call(this, fromPath, 'topic');

            }
        });

        
        /**
         * Return view class.
         */
        return TopicView;
    }
);

/**
 * @fileoverview Media Gallery.
 * @author jmerrifiel@gannett.com (Jay Merrifield)
 */
define('views/pages/media',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'baseappview',
    'sharedAdPosition',
    'views/modules/carousel/carousel-autosize',
    'views/modules/video',
    'views/modules/taboola',
    'views/modules/form/dropdown'
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    BaseAppView,
    SharedAdPosition,
    CarouselAutosizeGallery,
    Video,
    Taboola,
    Dropdown
)
    {
        /**
         * View class.
         */
        var MediaView = BaseAppView.extend({
            el: '#media-view',
            events: {
                'click .recommended, .more-from, .expando': 'mediaTabClick',
                'mouseout .media-playlist': 'mediaPlaylistMouseOut',
                'mouseover .media-playlist': 'mediaPlaylistMouseIn',
                'click .media-playlist a': 'changeMediaClick',
                'click .sidenav li.sub': 'sectionHighlight',
                'click': 'userInteraction'
            },
            initialize: function(options){
                options = $.extend(true, {
                        delay: {
                            playlistAutoClose: 250
                        },
                        animations: {
                            cinematic: {
                                change: {
                                    fadeOut: {
                                        duration: 300,
                                        easing: 'ease-in-out'
                                    },
                                    fadeIn: {
                                        duration: 300,
                                        easing: 'ease-in-out'
                                    }
                                }
                            }
                        }
                    }, options);

                _.bindAll(this, 'switchToNextVideo', 'handleResizeWindow');
                this.win = App.get('win');
                this.scrollEl = App.get('scrollEl');
                this.breakingBar = App.get('breakingEl');

                this.win.on('resize.' + this.cid, _.throttle(this.handleResizeWindow, 50));

                this.playlistTimer = null;
                this.init = false;

                this.subviews = {};

                // call base class initialize
                BaseAppView.prototype.initialize.call(this, options);

                var section = $('.sidenav > li.sub-active');
                this.lastSectionName = section.attr('data-section');

            },
            getAd: function() {
                this.subviews.skinad = new SharedAdPosition({
                    el: this.$('.partner-media-ad'),
                    adSizes: ['cinematicvideoskin'],
                    adPlacement: 'skin_media',
                    adType: 'skinmedia',
                    defaultPosition: true
                });
            },
            handleResizeWindow: function(){
                if(this.browse) this.columnize(this.$el);
            },
            beforePageReveal: function(fromPath, toPath, htmlFrag){
                if (!this.isCinematicPath(toPath)){
                    this.columnize(htmlFrag);
                }
            },
            afterPageReveal: function(fromPath, toPath){
                if (this.isCinematicPath(toPath)){
                    // hack to restore fixed position in webkit browsers
                    this.$el.css({'-webkit-transform':'none',
                                '-webkit-perspective': 0});
                    this.asset_type = null;
                    if (toPath.indexOf('/gallery') !== -1){
                        this.asset_type = 'gallery';
                        this._initializeGallery();
                    }else if (toPath.indexOf('/photo') !== -1){
                        this.asset_type = 'photo';
                        this._initializeImage(this.$el);
                    }else if (toPath.indexOf('/video') !== -1){
                        this.asset_type = 'video';
                        this._initializeVideo(this.$el);

                        // Get the ad on cinematic view for video assets
                        this.getAd();
                    }
                    this.browse = false;
                    if (!this.isCinematicPath(fromPath)){
                        this.playlistStuckOpen = false;
                        this.delayClosePlaylist();
                        if (fromPath){
                            // set the back url if we have one, otherwise it defaults to '/media'
                            // fromPath doesn't start with '/'
                            this.$('.back-to-media').attr('href', '/' + fromPath);
                        }
                    }

                } else {
                    // Browse view.
                    this._initializeBrowse();
                }
                this.handleResizeWindow();

                if (!this.subviews.filterDropdown) {
                    this.subviews.filterDropdown = new Dropdown({
                        el: this.$('.media-view-sort-by-dropdown')
                    });
                }
            },

            getRevealAppLoader: function(){
                return '<article id="media-view" class="ui-loading dark-medium"></article>';
            },

            // this needs to be here to prevent default behavior until we can provide a temporary loader for sliding animations
            animateChangePagePostData: function(fromPath, toPath, htmlFrag, paused){
                if (this.isCinematicPath(toPath)){
                    if (!this.isCinematicPath(fromPath)){
                        // transition left to cinematic view
                        return this.slide(htmlFrag, 'left', this.options.animations.slide.duration,
                            this.options.animations.slide.easing);
                    }else{
                        // cinematic to cinematic!
                        return this._fadeInNewCinematicContent(toPath, htmlFrag);
                    }
                }else{ // this isn't a cinematic path
                    if (this.isCinematicPath(fromPath)){
                        // but we're on cinematic mode, slide out cinematic to the right
                        return this.slide(htmlFrag, 'right', this.options.animations.slide.duration,
                            this.options.animations.slide.easing);
                    }else{
                        return BaseAppView.prototype.animateChangePagePostData.apply(this, arguments);
                    }
                }
            },

            animateChangePagePreData: function(fromPath, toPath){
                if (!this.isCinematicPath(fromPath) && !this.isCinematicPath(toPath)) {
                    // only switching from browse to browse has a preData animation
                    return this.changeBrowseSection(fromPath, toPath);
                }
            },
            changeBrowseSection: function(fromPath, toPath){
                var navItems = this.$('.sidenav');
                var fromSectionPath = this._getSubSectionPath(fromPath);
                var toSectionPath = this._getSubSectionPath(toPath);
                if (fromSectionPath === toSectionPath){
                    return;
                }
                var upPromise, downPromise;
                navItems.children().each(function(idx, item){
                    item = $(item);
                    var dataSection = item.attr('data-section') || '';
                    if (dataSection === fromSectionPath){
                        upPromise = item.find('.media-sidenav-sublist').slideUp(250);
                        item.removeClass('active');
                    }else if (dataSection === toSectionPath){
                        downPromise = item.find('.media-sidenav-sublist').slideDown(250);
                        item.addClass('active');
                    }
                });
                if (upPromise){
                    this.registerAnimation(upPromise.promise());
                }
                if (downPromise){
                    this.registerAnimation(downPromise.promise());
                }
                return $.when(upPromise, downPromise);
            },
            _getSubSectionPath: function(path){
                path = path.replace(/^media\/((latest|popular)\/)?/, '');
                if (path){
                    var slashIndex = path.indexOf('/');
                    if (slashIndex === -1){
                        return path;
                    }else{
                        return path.substring(0, slashIndex);
                    }
                }else{
                    return '';
                }
            },
            isCinematicPath: function(path){
                return path && path.indexOf('/cinematic') !== -1;
            },
            _fadeInNewCinematicContent: function(toPath, htmlFrag){
                return $.Deferred(_.bind(function(defer){
                    // we wait until the request finishes
                    this._swapRelatedMedia(htmlFrag);
                    this._swapNavBar(htmlFrag);
                    this._swapMainView(htmlFrag, defer);
                }, this)).promise();
            },
            _swapNavBar: function(htmlFrag){
                var fadeOutPromise = this.animate(this.$('.cinematic-side-nav-ul'), 'opacity', 0,
                    this.options.animations.cinematic.change.fadeOut.duration,
                    this.options.animations.cinematic.change.fadeOut.easing);
                fadeOutPromise.done(_.bind(function() {
                    var newNav = htmlFrag.find('.cinematic-side-nav-ul');
                    newNav.css('opacity', 0);
                    this.$('.cinematic-side-nav-ul').replaceWith(newNav);
                    this.animate(newNav, 'opacity', 1,
                        this.options.animations.cinematic.change.fadeIn.duration,
                        this.options.animations.cinematic.change.fadeIn.easing);
                }, this));
            },
            _swapMainView: function(htmlFrag, deferred){
                var fadeOutPromise = this.animate(this.$('.media-main-view'), 'opacity', 0,
                                this.options.animations.cinematic.change.fadeOut.duration,
                                this.options.animations.cinematic.change.fadeOut.easing);
                fadeOutPromise.done(_.bind(function() {
                        var newView = htmlFrag.find('.media-main-view');
                        newView.css('opacity', 0); // hide the new so it fades in
                        this.$('.media-main-view').replaceWith(newView);
                        if (!newView.length){
                            // something went wrong, resolve the animation cause fadeTo doesn't
                            // work on empty elements
                            deferred.resolve();
                        }else{
                            var fadeInPromise = this.animate(newView, 'opacity', 1,
                                    this.options.animations.cinematic.change.fadeIn.duration,
                                    this.options.animations.cinematic.change.fadeIn.easing);
                            fadeInPromise.done(_.bind(function(){
                                deferred.resolve();
                            }, this));
                        }
                    }, this)
                );
            },
            _swapRelatedMedia: function(htmlFrag){
                var fadeOutPromise = this.animate(this.$('.recommended'), 'opacity',
                                            this.options.animations.cinematic.change.fadeOut.duration,
                                            this.options.animations.cinematic.change.fadeOut.easing);
                fadeOutPromise.done(_.bind(function() {
                        var newView = htmlFrag.find('.recommended');
                        newView.css('opacity', 0); // hide the new so it fades in
                        this.$('.recommended').replaceWith(newView);
                        if (newView.length){
                            this.animate(newView, 'opacity', 1,
                                this.options.animations.cinematic.change.fadeIn.duration,
                                this.options.animations.cinematic.change.fadeIn.easing);
                        }
                    }, this)
                );
            },
            _initializeGallery: function(){
                var html = this.$('.galleries');
                var galleryId = html.data().galleryId || 0;
                this.subviews.carousel = new CarouselAutosizeGallery({
                    ads:false,
                    el: this.$el,
                    gallerySelector: html,
                    scrollerColor: 'dark',
                    verticalAdjust: 117
                });

                // Make request to taboola to get recommended galleries.
                this.subviews.taboola = new Taboola();
                this.subviews.taboola.getRelated(this.showRecommended, 'photo', 'photo', 10, null, galleryId);
            },
            _initializeVideo: function(html){
                var videoId = this.$('.video .videoObject').attr('id');
                this.subviews.video = new Video({
                    el: html,
                    onVideoComplete: this.switchToNextVideo,
                    autostart: true
                });

                // Make request to taboola to get recommended videos.
                this.subviews.taboola = new Taboola();
                this.subviews.taboola.getRelated(this.showRecommended, 'video', 'video', 10, null, videoId);
            },
            userInteraction: function(){
                if (this.switchVideoTimer){
                    clearTimeout(this.switchVideoTimer);
                }
            },
            switchToNextVideo: function(){
                var nextItem = this.$('.more-from .active').next();
                if (nextItem.length){
                    this.switchVideoTimer = setTimeout(function(){
                        nextItem.find('a').click();
                    }, 5000); // 5 seconds (5 * 1000)
                }
            },
            _initializeImage: function(html){
                App.lazyLoadImage($(html).find('.viewport img'), 'data-large-src');
            },

            destroyModules: function() {
                clearTimeout(this.switchVideoTimer);
                BaseAppView.prototype.destroyModules.apply(this, arguments);
            },

            destroy: function(removeEl){
                this.win.off('.' + this.cid);
                // call base class destroy
                BaseAppView.prototype.destroy.call(this, removeEl);
            },
            changeMediaClick: function(e){
                // this function only changes the highlight state
                // actual navigation is handled by the routes

                var $ele = $(e.target);

                this.$('.playlist li.active').removeClass('active');
                $ele.closest('li').addClass('active');

                if ($ele.closest('nav').hasClass('recommended')) {
                    var $img = $ele.closest('img');
                    var response_id = App.get('taboolaResponseID');
                    var item_type = $img.attr('data-type');
                    var item_id = $img.attr('data-id');
                    Taboola.prototype.registerTaboolaClick(item_id, item_type, response_id);
                }
            },

            mediaTabClick: function(e){
                var $playlist = this.$('.media-playlist');
                var $target = $(e.target).closest('li');
                if ($target.hasClass('expando')){
                    if ($playlist.hasClass('open')){
                        this.playlistStuckOpen = false;
                        $playlist.removeClass('open');
                    }else{
                        this.playlistStuckOpen = true;
                        $playlist.addClass('open');
                    }
                }else if ($target.hasClass('tab')){
                    $playlist.addClass('open');
                    if (!$target.hasClass('active')){
                        $playlist.find('.media-tabs .active').removeClass('active');
                        $target.addClass('active');
                        $playlist.find('.playlist').addClass('hidden');
                        $playlist.find('.' + $target.attr('for')).removeClass('hidden');
                    }
                }
            },
            mediaPlaylistMouseOut: function(){
                if (!this.playlistStuckOpen){
                    this.delayClosePlaylist();
                }
            },
            mediaPlaylistMouseIn: function(){
                clearTimeout(this.playlistTimer);
            },
            delayClosePlaylist: function(){
                    this.$('.media-playlist').removeClass('initial');
            },

            /**
             * Initialize browse / overview page.
             */
            _initializeBrowse: function() {
                this.gridWrapper = this.$('.grid-wrapper');
                this.browse = true;
            },

            /**
             * Create columns for the browse view, based on page width.
             */
            columnize: function(htmlFrag) {
                var columnSize = 360;
                var gridItems = htmlFrag.find('.medialistitems');
                var pageWidth = $(window).width();
                var containerWidth = pageWidth - 130 - 31;
                var columns = Math.floor(containerWidth / columnSize);
                if (columns < 1){
                    columns = 1;
                }
                htmlFrag.find('.media-content').width(columns * columnSize);
                gridItems.removeClass('mediaview-featured');
                gridItems.slice(0, columns).addClass('mediaview-featured');
            },

            /**
             * Toggle subsections.
             * @param {Event} e Click event
             */
            sectionHighlight: function(e) {
                var target = $(e.currentTarget);
                if (target.hasClass('active') && !$(e.target).attr('href')) {
                    var activeSub = target.children('div');
                    if (target.hasClass('collapsed')) {
                        this.registerAnimation(activeSub.slideDown(250).promise());
                        target.removeClass('collapsed');
                    } else {
                        this.registerAnimation(activeSub.slideUp(250).promise());
                        target.addClass('collapsed');
                    }
                }
            },

            /*
             * Find taboola template for recommended galleries and populate it.
             */
            showRecommended: function(data) {
                var more = $('#mediaview-recommended-template');
                if (more.length === 1) {
                    var compiled = _.template(more.html(), {data: data.list});
                    $('#mediaview-cinematic-recommended').append(compiled);
                }
            }
        });

        /**
         * Return view class.
         */
        return MediaView;
    }
);

/**
 * @fileoverview Blog view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 */
define('views/pages/blog',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'views/pages/stag-front',
    'views/modules/twitter',
    'views/modules/blogs'
    ],
    function(
        $,
        _,
        Backbone,
        App,
        PubSub,
        StagFront,
        TwitterView,
        Blogs
    ) {

        /**
         * View class.
         */
        var BlogView = StagFront.extend({

            // View element.
            el: '#blog-card',

            /**
             * Instantiate dependencies and render the view.
             */
            _initializeTopic: function(fromPath, ignoredPageType){
                // Initialize the Twitter Module.
                this.subviews.twitter = new TwitterView({
                    el : '.stag .mod.tweets',
                    num_tweets : 9,
                    columns: 3
                });

                // Initialize the Blogs module
                this.subviews.blogs = new Blogs({
                    el : '.stag .mod.blogs'
                });

                // call base class initialize
                StagFront.prototype._initializeTopic.call(this, fromPath, 'blog');
            }

        });


        /**
         * Return view class.
         */
        return BlogView;
    }
);

/**
 * @fileoverview User Auth view.
 * @author jheiner@usatoday.com (John Heiner)
 */
define('views/pages/userauth',[
    'jquery',
    'underscore',
    'backbone',
    'app',
    'pubsub',
    'baseview',
    'facebook',
    'fwinfo'
],
function(
    $,
     _,
     Backbone,
     App,
     PubSub,
     BaseView,
     Facebook,
     FwInfo
)
{


        /**
         * View class.
         */
        var UserAuthView = BaseView.extend({

            // View element.
            el: '#userauth-card',

            /**
             * Initialize view.
             * @param {Object} options View options passed during init.
             */
            initialize: function(options) {
                this.$top = App.get('scrollEl');

                // call base class initialize
                BaseView.prototype.initialize.call(this, options);

            },
            afterPageReveal: function(fromPath, toPath){
                App.set('currentCardPath', toPath);

                Facebook.init(function(){return;},true);

                $('.fb-login-button').attr( 'scope', Facebook.permissions() );
                Facebook.parse();
            },
            /**
             * Adjust the topic card to the top.
             */
            adjust: function() {
                this.$top.animate({scrollTop: 0}, 200);
            }

        });


        /**
         * Return view class.
         */
        return UserAuthView;
    }
);

/**
 * @fileoverview ContactUs Overlay.
 * @author Jay Merrifield
 */
define('views/pages/contactus-overlay',['jquery', 'underscore', 'backbone', 'state', 'app', 'simpleoverlay', 'views/modules/footer', 'pubsub'],
    function($, _, Backbone, StateManager, App, SimpleOverlay, Footer, PubSub) {
        var ContactUsView = SimpleOverlay.extend({

            additionalEvents: {
                'click': 'closeOverlayForm',
                'click .contactus-tabs a': 'changeTabs',
                'click .contact-us-faq a': 'expandFaq',
                'click .overlayForm': 'openOverlayForm',
                'click .faq-search': 'openSearchForm'
            },

            initialize: function(options) {
                this.currentTab = null;
                this.overlayOpen = false;
                // call base class initialize
                SimpleOverlay.prototype.initialize.call(this, options);
            },
            closeOverlayForm: function(e){
                if (this.overlayOpen){
                    this.overlayOpen.fadeOut(200);
                    this.overlayOpen = null;
                    return false;
                }
            },

            openSearchForm: function(e){
                PubSub.trigger('masthead:expand', true);
                return false;
            },

            afterPageReveal: function(fromPath, toPath, paused){
                this.$contactUsTabs = this.$('.contactus-tabs');
                this.$clarificationsModal = this.$('#clarifications');
                this.$letterToEditorModal = this.$('#letterToEditor');
                this.subviews.footer = new Footer();
                SimpleOverlay.prototype.afterPageReveal.apply(this, arguments);
            },

            expandFaq: function(e){
                var $link = $(e.target);
                var $answer = $link.next();
                if ($answer.is(':visible')){
                    $link.parent().removeClass('active');
                    $answer.slideUp(200);
                }else{
                    $link.parent().addClass('active');
                    $answer.slideDown(200);
                }
            },

            changeTabs: function(e){
                var $target = $(e.target);
                var tab = $target.attr('tab');
                if (tab && this.currentTab !== tab){
                    this.currentTab = tab;
                    this.$contactUsTabs.find('.active').removeClass('active');
                    this.$('.contact-us-faq').hide();
                    $target.parent().addClass('active');
                    this.$('.' + tab).show();
                }
            },
            openOverlayForm: function(e){
                var $target = $(e.target);
                var flyoutId = $target.data('flyout');
                if (flyoutId){
                    if (this.overlayOpen){
                        this.closeOverlayForm();
                        return;
                    }
                    if (flyoutId === 'clarifications'){
                        this.overlayOpen = this.$clarificationsModal;
                    }else{
                        this.overlayOpen = this.$letterToEditorModal;
                    }
                    this.overlayOpen.fadeIn(200);
                }
                return false;
            }
        });
        return ContactUsView;
    }
);
/**
 * @fileoverview Sitemap view.
 * @author bbagley@usatoday.com (Brendan Bagley)
 *
 */

define('views/pages/sitemap',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'views/pages/base-page',
    'views/modules/ajax-widget',
    'baseappview',
],
function(
    $,
    _,
    Backbone,
    PubSub,
    App,
    BasePage,
    AjaxWidget,
    BaseAppView
)
    {

        /**
         * View class.
         */
        var SitemapView = BaseAppView.extend({
            // View element.
            el: '.sitemap',
            /**
             * Initialize view.
             */
            initialize: function(options) {
                //calls super method
                BaseAppView.prototype.initialize.call(this, options);
            }

        });


        /**
         * Return view class.
         */
        return SitemapView;
    }
);

/**
 * @fileoverview Handles metered ad overlays
 * @author Jay Merrifield <jmerrifiel@gannett.com>
 */

define('views/modules/partner/overlay-ad-asset',[
    'jquery', 
    'underscore', 
    'state',
    'views/modules/partner/overlay-ad-base',
    'meteredAdPosition',
    'adLogger'
],
function(
    $, 
    _, 
    StateManager,
    OverlayAdBase,
    MeteredAdPosition,
    AdLogger
) {
    
    var OverlayMeteredAd = OverlayAdBase.extend({

        /**
         * Initialize view.
         */
        initialize: function(options) {
            options = $.extend({
                adSizes: ['elastic'],
                adPlacement: 'transition',
                rateMeterId: 'transition'
            }, options);

            _.bindAll(this, 'onAdReady', 'onResize');

            // call base class initialize
            OverlayAdBase.prototype.initialize.call(this, options);

            this.loadAdPlacement();

            AdLogger.logDebug('Partner Metered Overlay initialized', this);
        },

        loadAdPlacement: function() {
            var pageInfo = StateManager.getActiveApp().pageInfo;
            this.subviews.ad = new MeteredAdPosition({
                el: this.$placement,
                adSizes: this.options.adSizes,
                adPlacement: this.options.adPlacement,
                rateMeterId: this.options.rateMeterId,
                pageInfo: pageInfo,
                onAdReady: this.onAdReady,
                beforeAdRender: this.onResize
            });

            if (this.subviews.ad.tickMeter(pageInfo.excludeTransitionAd)) {
                // if we're not excluding a transitionAd on this page and the meter has ticked to 0,
                // we want to prefetch an add and then show it (through onAdReady callback)
                this.subviews.ad.prefetchAd();
            } else {
                // overlay ads are targeted based on page
                // if we aren't rendering an ad, we don't need this position and can destroy it
                this.destroyAdPosition();
            }
        },

        destroyAdPosition: function() {
            if (this.subviews.ad) {
                this.subviews.ad.destroy();
                this.subviews.ad = null;
            }
        },

        refresh: function() {
            this.destroyAdPosition();
            this.loadAdPlacement();
        }
    });

    return OverlayMeteredAd;
});

/**
 * @fileoverview Global overlay (nav) module view.
 * @author erik.kallevig@f-i.com (Erik Kallevig)
 */
define('views/modules/overlay',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'appview',
    'baseappview',
    'state',
    'views/modules/partner/overlay-ad-asset',
    'views/modules/cards2'
],
    function(
        $,
        _,
        Backbone,
        PubSub,
        App,
        AppView,
        BaseAppView,
        StateManager,
        OverlayAssetAd,
        CardView
    ) {


        /**
         * View class.
         */
        var OverlayView = BaseAppView.extend({

            // View element.
            el: '#overlay',

            // Events.
            events: {
                'click .transition-wrap': 'close',
                'click .close-overlay': 'close'
            },

            /**
             * Initialize the view.
             * @param {Object=} options Init options.
             */
            initialize: function(options) {
                options = $.extend(true, {
                    template: '<div id="overlay" class="no-transition">' +
                        '<div class="content">' +
                        '<div class="transition-wrap">' +
                        '<article class="asset clearfix story ui-loading light-medium">' +
                        '</article></div>' +
                        '</div>' +
                        '<div class="film show"></div>' +
                        '</div>'
                });
                this.init = false;

                _.bindAll(this, 'close', 'updateArrowLinks');

                // Cached queries.
                this.win = App.get('win');
                this.scrollEl = App.get('scrollEl');
                this.nav = App.get('navEl');
                this.breaking = App.get('breakingEl');
                this.breakingWrap = App.get('breakingWrapEl');
                this.currentStoryIndex = -1;
                this.fromPath = null;
                this.storyCollection = [];
                this.animationIndex = 0;

                this.subviews = {};

                this.header = AppView.getHeader();

                // PubSub events.
                this.pubSub = {
                    'close:overlay': this.close,
                    'updateArrowLinks:overlay': this.updateArrowLinks
                };

                // Call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            setFixedPosition: function(offset){
                this.positionCloseButton('fixed');
                BaseAppView.prototype.setFixedPosition.apply(this, arguments);
            },

            animateChangePagePostData: function(fromPath, toPath, htmlFrag, paused) {
                var transition = htmlFrag.find('.transition-wrap');
                transition.css('height', this.win.height() - 40);
                return this.swapContent(this.$('.transition-wrap'), transition).done(_.bind(function(){
                    transition.css('height', '');
                }, this));
            },

            getRevealAppLoader: function(toPath){
                return this.options.template;
            },

            beforePageReveal: function(fromPath, toPath, htmlFrag, paused) {
                if (!this.appRevealed && fromPath !== null){
                    this.$el.find('.film').remove();
                }
            },

            afterPageReveal: function(fromPath, toPath, paused, ViewClass) {
                var story = this.$('.transition-wrap:first'),
                    storyArticle = story.find('.asset'),
                    winHeight = this.win.height();
                if (storyArticle.outerHeight() < winHeight) {
                    storyArticle.css({'min-height': winHeight});
                }
                this.fromPath = fromPath;
                // Initial page load, no ajax.
                //Moved section declaration outside of if so that it is not done twice
                var section = this.getSectionName();
                if (fromPath === null) {
                    // Initialize overlay.             

                    // Determine which section front should load
                    // behind depending on the story.
                    StateManager.preloadPath(section).done(_.bind(function(){
                        this.updateArrowLinks();
                    }, this));
                } else {
                    this.header.updateNavigation(section);
                }

                if (!this.init) {
                    this.initializeDom();
                    this.init = true;
                    this.currentStoryIndex = this.getBestStoryIndex(toPath);
                    PubSub.trigger('open:overlay');
                }

                // Populate arrow links.
                this.updateArrowLinks();

                // Init story view.
                if (ViewClass){
                    this.subviews.storyView = new ViewClass({
                        el: story
                    });
                }

                // persistent transition metered ad
                // we don't put the overlay ad in subviews because we want it to persist between page loads
                if (this.transitionAd) {
                    this.transitionAd.refresh();
                } else {
                    var transitionAd = this.$('.partner-overlay');
                    if (transitionAd.length) {
                        this.transitionAd = new OverlayAssetAd({
                            el: transitionAd.eq(0)
                        });
                    }
                }

                this.positionCloseButton('fixed');
            },
            initializeDom: function(){
                // Get template.
                this.arrowWrapTemplate = this.$('#overlay-arrow-wrap');

                // Cache container query.
                this.arrowContainer = this.$('.overlay-arrows');

                this.film = this.$('.film');
                this.collection = this.$('.content');
            },

            animateRevealApp: function(fromPath, toPath, preload) {
                var transitionWrap = this.$('.transition-wrap');
                var height = this.win.height() - 40;
                if (this.isSafari5 || !this.useCSSTransforms){
                    transitionWrap.css({'height': height});
                    return this.show();
                }
                transitionWrap.css({'height': height, overflow: 'hidden', opacity: 0});
                transitionWrap[0].style[this.transformCssName] = 'scale(0.4)';
                transitionWrap[0].style[this.transformOriginCssName] = '50% ' + (height * 0.25) + 'px';
                transitionWrap[0].style[this.transitionCssName] = this.transformCssHyphenName + ' 300ms linear, opacity 300ms linear';
                this.$el.show().css({opacity: 1, display: 'block'});

                var film = this.$('.film').removeClass('show');
                var filmPromise = this.animate(film, 'opacity', '.85', 300, 'linear');
                // need to let the browser render the non-zoomed-in version before triggering the animation
                _.delay(_.bind(function(){
                    transitionWrap[0].style[this.transformCssName] = 'scale(1.0)';
                    transitionWrap[0].style.opacity = 1;
                }, this));

                var deferred = this.registerTransitionEndListener(transitionWrap);
                $.when(deferred, filmPromise).done(_.bind(function(){
                    this.clearTransition(transitionWrap);
                    transitionWrap[0].style[this.transformOriginCssName] = '';
                    // transitionWrap.css({height: '', overflow: 'visible'});
                }, this));
                return deferred.promise();
            },

            destroyModules: function() {
                if (this.transitionAd) {
                    this.transitionAd.close();
                }
                BaseAppView.prototype.destroyModules.apply(this, arguments);
            },

            beforeAppRemove: function(fromPath, toPath){
                if (this.transitionAd) {
                    this.transitionAd.destroy();
                }
                this.positionCloseButton('absolute', App.getScrollPosition());
            },

            animateRemoveApp: function(fromPath, toPath) {
                if (this.isSafari5){
                    return this.hide();
                }
                if (this.appRevealed){
                    return this.animate(this.$el, 'opacity', 0, 250);
                }else{
                    this.$el.css('z-index', 1000);
                    return this.hide(true);
                }
                this.header.updateNavigation(toPath);
            },

            /**
             * Update arrow links and toggle disabled state as necessary.
             */
            updateArrowLinks: function() {
                if (this.currentStoryIndex === -1){
                    // make one last attempt to figure out what our index in incase something changed
                    this.currentStoryIndex = this.getBestStoryIndex(window.location.pathname);
                    if (this.currentStoryIndex === -1){
                        this.arrowContainer.removeClass('show');
                        return;
                    }
                }
                var collection = this.getStoryCollection();

                if (this.prevAsset === collection[this.currentStoryIndex - 1] &&
                    this.nextAsset === collection[this.currentStoryIndex + 1]){
                    return;
                }
                this.prevAsset = collection[this.currentStoryIndex - 1];
                this.nextAsset = collection[this.currentStoryIndex + 1];

                // Populate arrow links.
                var arrowDom = this.buildArrowDom(this.prevAsset, 'previous');
                arrowDom = arrowDom.add(this.buildArrowDom(this.nextAsset, 'next'));
                this.arrowContainer.empty().append(arrowDom);
                this.arrowContainer.addClass('show');
            },

            buildArrowDom: function(asset, direction) {
                var disabled = (!asset);
                if (!asset) {
                    asset = {
                        disabled: 'disabled'
                    };
                } else {
                    asset.disabled = '';
                }
                asset.dir = direction;

                // Check for square photo.
                if (asset.photo && asset.photo.crops) {
                    if (asset.photo.crops['1_1'] && asset.photo.crops['1_1'].indexOf('.jpg') !== -1) {
                        asset.image = asset.photo.crops['1_1'];
                        // Alter path to resize square to 64px.
                        var transmogEnd = '_r64.jpg?3aa4db7cc8ccd5d587e4ef60ee4f4bfbf4814675';
                        asset.image = asset.image.replace('.jpg', transmogEnd);
                    }
                }

                var arrow = $(_.template(this.arrowWrapTemplate.html(), asset));
                if (disabled){
                    if (this.isApple){
                        arrow.css({display: 'none'});
                    }else{
                        arrow.css({'z-index': 1});
                    }
                }else if (this.isApple){
                    arrow.find('.preview').remove();
                }
                return arrow;
            },

            /**
             * This function sets the close button to either fixed or absolute positioning.
             * @param {String} positionType Either 'fixed' or 'absolute'.
             * @param {Number} [scrollPosition] position of where the close button should be placed, defaults to 0
             * @param {jQuery} [closeStoryWrap] The story wrap parent of the close button to position, defaults to this.$('.close-wrap').
             */
            positionCloseButton: function(positionType, scrollPosition, closeStoryWrap) {
                var closeWrap = closeStoryWrap ? closeStoryWrap.find('.close-wrap') : this.$('.close-wrap');
                if (positionType === 'absolute') {
                    closeWrap.css({ 'position': positionType, 'top': scrollPosition || 0 });
                } else {
                    closeWrap.css({ 'position': positionType, 'top': '' });
                }
            },

            /**
             * Close the overlay.
             * @param {Event} e Click event.
             */
            close: function(e) {
                if (e && e.target !== e.currentTarget){
                    // trap clicks inside the transition wrap to prevent them from closing the overlay
                    return;
                }
                var utvalue = $(e.currentTarget).attr("data-ht") || 'modalclose';
                PubSub.trigger('heattrack', utvalue);
                StateManager.navigateToPreloadedUrl();
                if (e) return false;
            },

            /**
             * Clean up view.
             * Removes event handlers and element (optionally).
             * @param {Boolean} removeEl Option to also remove View from DOM.
             */
            destroy: function(removeEl) {
                // Call base class initialize
                BaseAppView.prototype.destroy.call(this, removeEl);
            },

            getSectionName: function() {
                var section = '',
                    pageInfoObj = this.pageInfo,
                    path;
                if (pageInfoObj && (pageInfoObj.ss || pageInfoObj.ssts)) {
                    path = pageInfoObj.ss;
                    if (!path){
                        path = pageInfoObj.ssts;
                        var split = path.indexOf('/');
                        if (split > 0){
                            path = path.substring(0, split);
                        }
                        if (_.indexOf(CardView.prototype.cards, path) === -1){
                            path = null;
                        }
                    }
                    App.set('ss', path);
                    section = path;
                    if (path.indexOf('/') > 0) {
                        section = path.substring(0, path.indexOf('/'));
                    }

                    if (section === 'home') {
                        section = '/';
                    } else {
                        section = section + '/';
                    }
                }
                return section;
            },

            getBestStoryIndex: function(toPath){
                if (toPath && toPath[0] !== '/'){
                    toPath = '/' + toPath;
                }
                // there's a chance the same story could exist multiple times in the carousel
                // so we search based on the currentIndex
                var collection = this.getStoryCollection();
                if (!collection || collection.length === 0){
                    return -1;
                }
                var min = -1, max = -1;
                var current = this.currentStoryIndex;
                if (current === -1){
                    current = 0;
                }

                var i;
                for (i = current; i >= 0; i--){
                    if (collection[i].links.html === toPath){
                        min = i;
                        break;
                    }
                }
                for (i = current; i < collection.length; i++){
                    if (collection[i].links.html === toPath){
                        max = i;
                        break;
                    }
                }
                if (max === -1 && min === -1){
                    // Story not found. Add story to the beginning of 
                    // the preloaded front's collection.
                    var story = {
                        "links": {
                            "html": toPath
                        }
                    };
                    this.storyCollection.unshift(story);
                    return 0;
                }else if (max === -1){
                    return min;
                }else if (min === -1){
                    return max;
                }else{
                    // we have a duplicate, find the article closests to the current
                    if ((current - min) < (max - current)){
                        return min;
                    }else{
                        return max;
                    }
                }
            },

            getStoryCollection: function(){
                if (this.storyCollection.length === 0) {
                    var pageInfo = StateManager.getPreloadedPageInfo();
                    var collection = pageInfo && pageInfo.asset_collection;
                    if (collection) {
                        this.storyCollection = _.filter(collection, function(item) {
                            if(item.links.html.indexOf("http")!==0) {
                                return item.headline && item.links && item.links.html;
                            }
                        });
                    }
                }
                return this.storyCollection;
            },

            animateChangePagePreData: function(fromPath, toPath) {
                var deferred = $.Deferred();
                var winHeight = this.win.height() - 40;
                var scrollPosition = App.getScrollPosition();
                var activeTransitionWrap = this.$('.transition-wrap:last');
                this.prepareContentForTransition(activeTransitionWrap, scrollPosition, winHeight);

                var htmlFrag = $(this.options.template);

                var stagedTransitionWrap = htmlFrag.find('.transition-wrap');
                stagedTransitionWrap.css({position:'absolute'});
                stagedTransitionWrap.attr('data-animation-index', ++this.animationIndex);
                this.prepareContentForTransition(stagedTransitionWrap, 0, winHeight);

                this.scrollEl.scrollTop(0);

                this.collection.append(stagedTransitionWrap);

                this.positionCloseButton('absolute', scrollPosition, activeTransitionWrap);

                var nextStoryIndex = this.getBestStoryIndex(toPath);
                if (this.currentStoryIndex !== -1 && nextStoryIndex !== -1){
                    // aha, we know which direction to animate
                    activeTransitionWrap.css('left', '0%');
                    var activeDest, stagedDest = '0%';
                    if (this.currentStoryIndex > nextStoryIndex){
                        stagedTransitionWrap.css('left', '-100%');
                        activeDest = '100%';
                    }else{
                        stagedTransitionWrap.css('left', '100%');
                        activeDest = '-100%';
                    }

                    var promise = $.when(this.animate(activeTransitionWrap, 'left', activeDest, 350, 'ease-in-out'),
                        this.animate(stagedTransitionWrap, 'left', stagedDest, 350, 'ease-in-out'));
                    promise.done(_.bind(function() {
                        this.clearTransition(activeTransitionWrap);
                        activeTransitionWrap.remove();
                        if (parseInt(stagedTransitionWrap.attr('data-animation-index'), 10) === this.animationIndex){
                            this.resetContentTransition(stagedTransitionWrap);
                        }
                        deferred.resolve();
                    }, this));
                    // No slideDirection specified, so fade/prev-story load required.
                } else {
                    deferred = this.swapContent(activeTransitionWrap, stagedTransitionWrap);
                }
                this.currentStoryIndex = nextStoryIndex;
                return deferred.promise();
            },
            prepareContentForTransition: function(transitionWrap, scrollPosition, winHeight){
                transitionWrap.css({height:winHeight});
                transitionWrap.children().css({'top': -1 * scrollPosition});
            },
            resetContentTransition: function(transitionWrap){
                transitionWrap.css({position:'relative'});
            }

        });


        /**
         * Return view class.
         */
        return OverlayView;
    }
);

/**
 * @fileoverview Application class for stand-alone interactive assets.
 * @author jlcross@gannett.com (Jon Cross)
 */
define('views/modules/interactivesApp',[
    'jquery',
    'underscore',
    'backbone',
    'pubsub',
    'app',
    'baseappview',
    'state'
],
    function(
        $,
        _,
        Backbone,
        PubSub,
        App,
        BaseAppView,
        StateManager
    ) {


        /**
         * View class.
         */
        var InteractivesAppView = BaseAppView.extend({

            // View element.
            el: '#interactive',

            // Events.
            events: {},

            /**
             * Initialize the view.
             * @param {Object=} options Init options.
             */
            initialize: function(options) {
                this.init = false;

                this.subviews = {};

                // Call base class initialize
                BaseAppView.prototype.initialize.call(this, options);
            },

            afterPageReveal: function(fromPath, toPath, paused, ViewClass) {
                var interactive = this.$('.asset.standalone');
                this.init = true;

                // Init interactives view.
                if (ViewClass){
                    this.subviews.interactivesView = new ViewClass({
                        el: interactive
                    });
                }
            }
        });


        /**
         * Return view class.
         */
        return InteractivesAppView;
    }
);

//The build will inline common dependencies into this file.
;
define("common", function(){});
